在 python 中使用命令行开关或参数



我是python的新手,使用命令行args或在python中切换。我正在尝试编写此代码,该代码生成基本路径以创建目录。我的代码:

import os
import uuid
import datetime
from datetime import date
import subprocess
import sys
today = date.today()
currenttime = ('JT'+datetime.datetime.now().strftime("%H%M%S"))
currentday=('JD'+str(today.day))
currentyear=('JY'+str(today.year))
#param1=sys.argv[1]
step4='dataprep'
source_folder = input('enter existing dir path: ')
if os.path.isdir(source_folder):
    dir_path = source_folder
else:
    dir_path = os.path.join('root/PnG/bd_proc01/',step4,currentyear,currentday,currenttime, 
                          '{}'.format(str(uuid.uuid1())))
os.makedirs(dir_path)
print(dir_path)
#converting dir_path to test
test=dir_path.replace("/", "_")
print(test)

所以我的问题是,我如何通过运行如下所示的脚本来使用命令行开关生成相同的路径,而不是像我在脚本中所做的那样传递它们? 而且它的脚本应该能够查找现有路径(如果提供(而不是生成一个。

pngbdp_step1_upload.py -a root -b test -c bd_proc01 -d uploadout_dataprepin -p JY2017/JD331/JT231450/UUID_b3983ebc-d3c9-11e7-ae72-000d3a0097c5 -x /mnt/localjobfiles/filesnfolderstoupload.txt

或者有人可以通过在命令行中像这样运行来阐明或帮助我生成基本路径。

抱歉,如果我的问题含糊不清...

感谢

亚尔7002

我认为您正在寻找模块参数解析。它允许您解析提供给脚本的命令行参数。有关更多信息,请访问 https://docs.python.org/3/library/argparse.html 。这就是一切的总结。以下是文档中的示例代码:导入参数解析

parser = argparse.ArgumentParser(description='Process some integers.') # just some nice feature
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                help='an integer for the accumulator') #add posibility for argument
parser.add_argument('--sum', dest='accumulate', action='store_const',
                const=sum, default=max,
                help='sum the integers (default: find the max)') #add flag
args = parser.parse_args()
print(args.accumulate(args.integers))

您正在寻找argparse模块。您可以使用它来解析命令行参数。文档中有很多很好的例子。

最新更新