[英]How to specify python arguments except 0th argument
如果您使用參數調用python,即
python script.ps arg1, arg2, arg2
sys.argv [0]是script.ps,腳本名稱
如何引用和保存除0th參數之外的python腳本的ALL參數的值。
這是我的劇本
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
argparse
在這種情況下可以為您提供幫助,這是一個非常有用的工具。
這是帶有多個參數的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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.