【问题标题】:How to implement optional positional parameter in Python如何在 Python 中实现可选的位置参数
【发布时间】:2017-03-23 14:08:35
【问题描述】:

我有一个 Python 2.7 脚本返回一些数据。它还采用命令行位置参数:
filename.py -ip 172.17.12.12 -username admin

到目前为止,我已经使用以下函数(testargv.py)计算了 4 个参数:

def getopts(argv):
    opts = {}
    while argv:
        if argv[0][0] == '-':
            opts[argv[0]] = argv[1]
            argv = argv[2:]
        else:
            argv = argv[1:]
    return opts

myargs = getopts(argv)
if '-ip' in myargs:
    ip = myargs['-ip']
elif 'username' in myargs:
    username = myargs['-username']
elif 'password' in myargs:
    password = myargs['-password']
elif 'outfile' in myargs:
    outfile = myargs['-outfile']

这个单独的 .py 文件已导入现有项目(来自 testargv import getopts),在执行脚本之前发生以下情况:

ip = getopts(argv)['-ip']
username = getopts(argv)['-username']
password = getopts(argv)['-password']
outfile = getopts(argv)['-outfile']

我想让“outfile”成为可选的。所以用户不用输入,默认应该是
os.getcwd() + '\' + 'Select.log'

我已尝试将以下内容添加到 testargv.py:

elif 'outfile' not in myargs:
    outfile = os.getcwd() + '\\' + 'Select.log'

或在程序代码中添加以下内容:

if getopts(argv)['-outfile']:
    outfile = getopts(argv)['-outfile']
else:
    outfile = cwd + '\\' + 'Select.log'

但是没有 -outfile 的程序仍然失败: outfile = getopts(argv)['-outfile']
KeyError: '-outfile'

【问题讨论】:

  • 我现在可以看到它可以实现的唯一方法是检查 getopts(argv) 的主脚本长度,如果它不是 4,则设置 outfile cwd + '\\' + 'Select.log',但这不是好方法,因为客户可能会省略另一个参数。我确实需要检查 outfile 的持久性

标签: python python-2.7 parameters optional


【解决方案1】:

一些建议:

  1. 尝试使用https://docs.python.org/2/library/argparse.html
  2. 如果不是,那么:
    • 不要多次调用getopts(argv),调用一次并将结果保存到变量中
    • 考虑使用dictget 方法,如果您要求的键不在字典中,它会返回None

所以只要改变:

if getopts(argv)['-outfile']:
   outfile = getopts(argv)['-outfile']
else:
   outfile = cwd + '\\' + 'Select.log'

进入:

outfile = getopts(argv).get('-outfile')
if not outfile:
   outfile = cwd + '\\' + 'Select.log'

或到:

outfile = getopts(argv).get('-outfile') or cwd + '\\' + 'Select.log'

【讨论】:

  • outfile = getopts(argv).get('-outfile') 或 cwd + '\\' + 'Select.log' 这个有帮助!非常感谢
猜你喜欢
  • 2020-09-01
  • 2019-03-21
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2013-01-28
  • 2014-12-29
相关资源
最近更新 更多