接受一个路径作为命令行参数,而不是python中的输入



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

我希望输入路径作为命令行参数使用cmd_parser.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")

由固定代码导致的错误(它也不再做它应该做的事情了)

usage: StackTestSorter.py [-h] [-v] directory
StackTestSorter.py: error: the following arguments are required: directory

而不是:

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=''
)
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

有(删除--help参数,因为它将自动添加):

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(
"directory",  # this will be a positional argument
help="a valid directory which contains the files to be sorted",
)
cmd_args = cmd_parser.parse_args()
path = cmd_args.directory

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

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

然后在cmd_args之后你可以写:

path = cmd_args.path