繁体   English   中英

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

[英]Using command line switches or args in 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

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

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

谢谢,

yaar7002

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

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模块。 您可以使用它来解析命令行参数。 文档中有很多很好的例子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM