我有一个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'
一些建议:
getopts(argv)
,只调用一次并将结果保存在变量中dict
的^{None
,以防您请求的密钥不在字典中所以只要改变一下:
分为:
或发送至:
相关问题 更多 >
编程相关推荐