【问题标题】:Accepting a path as a command line argument instead of an input in python接受路径作为命令行参数而不是 python 中的输入
【发布时间】:2022-12-07 19:34:29
【问题描述】:

我的任务是使用 python 创建一个应用程序来对给定目录中的文件进行排序。

我希望输入路径作为命令行参数使用 命令解析器.add_argument() 而不是在运行代码后被接受为正常输入。

该代码按预期执行,但我不希望将路径作为输入接收。

任何帮助是极大的赞赏

import os
import shutil
from argparse import ArgumentParser


def main():
    cmd_parser = ArgumentParser(description="Application")
    cmd_parser.add_argument(
        '-v', '--version',
        action='version',
        version='Application v0.0.1',
        help='show version of the application'
    )
    cmd_parser.add_argument(
        '-h', '--help',
        action='help',
        help='Please enter a valid directory which contains the files to be sorted'
    )
    cmd_args = cmd_parser.parse_args()
    try:
        globals()[cmd_args.action](cmd_args.file)
    except Exception as ex:
        print('[ERROR]', str(ex))
        sys.exit(1)


while True:
    directory = input("Please input the directory including the files: ")
    if not os.path.isdir(directory):
        print("Please input a valid directory")
    else:
        break

path = directory
os.chdir(path)
new_folder = "Sorted Files"
os.makedirs(new_folder)
path_2 = path+"/"+new_folder
os.chdir(path_2)
new_folder_doc = "Documents"
new_folder_texts = "Texts"
new_folder_images = "Images"
new_folder_other = "Other"
os.makedirs(new_folder_doc)
os.makedirs(new_folder_texts)
os.makedirs(new_folder_images)
os.makedirs(new_folder_other)


for file in os.listdir(path):
    file_path = os.path.join(path, file)
    if os.path.isfile(file_path):
        file_name = os.path.basename(file_path)
    if file_path.endswith('.png') or file_path.endswith('.gif') or file_path.endswith('.bmp') or\
            file_path.endswith('.jpg') or file_path.endswith('.jpeg') is True:
        shutil.move(file_path, new_folder_images)
        continue
    if file_path.endswith('.txt') or file_path.endswith('.ini') or file_path.endswith('.log') is True:
        shutil.move(file_path, new_folder_texts)
        continue
    if file_path.endswith('.pdf') or file_path.endswith('.docx') or file_path.endswith('.doc') or\
            file_path.endswith('.xls') or file_path.endswith('.xlsx') or file_path.endswith('.csv') is True:
        shutil.move(file_path, new_folder_doc)
        continue
    if file_path.endswith('.docx') or file_path.endswith('.txt') or file_path.endswith('.bmp') or \
            file_path.endswith('.png') is not True:
        shutil.move(file_path, new_folder_other)
        continue

my_folder = path  # your path here
count = 0
for root, dirs, files in os.walk(my_folder):
    count += len([fn for fn in files if fn.endswith(".pdf") or fn.endswith(".docx")
                  or fn.endswith(".doc") or fn.endswith(".xls") or fn.endswith(".xlsx") or fn.endswith(".csv")
                  or fn.endswith(".jpeg") or fn.endswith(".jpg") or fn.endswith(".bmp") or fn.endswith(".gif")
                  or fn.endswith(".png") or fn.endswith(".txt") or fn.endswith(".ini") or fn.endswith(".log")])
print(f"Organized {count} files")

【问题讨论】:

    标签: python sorting cmd command-line-arguments


    【解决方案1】:

    如果我理解正确的话,你所需要做的就是再添加一个参数,比如:

    cmd_parser.add_argument("-p", "--path", help="", required=True, default=False)
    

    然后在 cmd_args 之后你可以这样做:

    path = cmd_args.path
    

    【讨论】:

      【解决方案2】:

      而不是拥有:

      def main():
          cmd_parser = ArgumentParser(description="Application")
          cmd_parser.add_argument(
              '-v', '--version',
              action='version',
              version='Application v0.0.1',
              help='show version of the application'
          )
          cmd_parser.add_argument(
              '-h', '--help',
              action='help',
              help='Please enter a valid directory which contains the files to be sorted'
          )
          cmd_args = cmd_parser.parse_args()
          try:
              globals()[cmd_args.action](cmd_args.file)
          except Exception as ex:
              print('[ERROR]', str(ex))
              sys.exit(1)
      
      
      while True:
          directory = input("Please input the directory including the files: ")
          if not os.path.isdir(directory):
              print("Please input a valid directory")
          else:
              break
      
      path = directory
      

      有:

      cmd_parser = ArgumentParser(description="Application")
      cmd_parser.add_argument(
          '-v', '--version',
          action='version',
          version='Application v0.0.1',
          help='show version of the application'
      )
      cmd_parser.add_argument(
          '-h', '--help',
          action='help',
          help='Please enter a valid directory which contains the files to be sorted'
      )
      cmd_parser.add_argument(
          "directory",  # this will be a positional argument
          help="The path to a directory",
      )
      
      cmd_args = cmd_parser.parse_args()
      
      path = cmd_args.directory
      

      【讨论】:

        猜你喜欢
        • 2022-11-25
        • 2014-04-12
        • 1970-01-01
        • 2019-05-01
        • 1970-01-01
        • 2013-03-02
        • 2013-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多