如果你用参数调用python,即
python script.ps arg1, arg2, arg2
sys.argv [0]是script.ps,脚本的名称
如何引用和保存除第0个参数之外的python脚本的所有参数的值。
这是我的剧本
import sys, subprocess, socket, string
import wmi, win32api, win32con
for args in [item.strip('sender-ip=') for item in sys.argv[1:]]:
userIP = args
userloggedon = ""
# perform system lookup of IP address
userIP = "\\\\" + userIP
pst = subprocess.Popen(
["D:\pstools\psloggedon.exe", "-l", "-x", userIP],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = pst.communicate()
userLoggedOn = out.split('\n')[1].strip()
print 'userId={}'.format(userLoggedOn)
如果我的sender-ip是唯一的参数,即
,这个脚本就可以正常工作python script.ps sender-ip=10.10.10.10
但如果我用
调用它python script.ps email=joe@gmail.com, sender-ip=10.10.10.10
或
python script.ps email=joe@gmail.com sender-ip=10.10.10.10
或
python script.ps "email=joe@gmail.com, sender-ip=10.10.10.10"
你明白了......
它不起作用,因为它无法从sender-ip中提取IP地址。
我期望的输出是
userId=DOMAIN\username
而不是
userId=
或
userId=
userId=DOMAIN\username
答案 0 :(得分:1)
argparse
可以在这种情况下帮助你,这是一个非常有用的工具。
这是一个带有多个args的argparse
示例:
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())
args
将是一个包含参数的字典:
if args['foo'] == 'Hello':
pass # replace with code
if args['bar'] == 'World':
pass # replace with code
另请查看此处了解更多信息:
编辑:对于位置参数(例如pos_arg = value),请使用:
parser.add_argument('pos_arg', nargs='+', help='Description for positional argument')