如何在Python中实现可选的位置参数

2024-10-02 00:40:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python2.7脚本返回一些数据。它还接受命令行位置参数:
filename.py-ip 172.17.12.12-用户名管理

到目前为止,我已经用以下函数(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()+'\'+'选择.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']
键错误:'-outfile'


Tags: inpyip脚本logifusernamepassword
1条回答
网友
1楼 · 发布于 2024-10-02 00:40:36

一些建议:

  1. 尝试使用https://docs.python.org/2/library/argparse.html
  2. 如果没有,那么:
    • 不要多次调用getopts(argv),只调用一次并将结果保存在变量中
    • 考虑使用dict^{}方法,它返回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'

相关问题 更多 >

    热门问题