我google了很多,並閱讀了我認爲建議使用vars()的東西的argparse文檔。如預期的那樣,我得到命名空間違規,我只是無法弄清楚這個問題的路徑。python argparse:使用參數作爲列表的值
本質上,我想採取一個argparse多值參數,並從這些值創建一個列表,所以我可以通過它們運行一個for-loop。這是爲了與我們的VNX陣列連接,以重置所有開發人員環境中的數據快照。
當我運行該命令時,我可以看到argparse正確地獲取了值,但是它拋出了Namespace異常並且實際上並未使用參數的值。
非常感謝任何指導,甚至鏈接到一些更好的文檔,這將更好地解釋我的問題。我知道這個問題,以及我想如何解決這個問題,我只是不確定甚至讀什麼(或谷歌)來解決這個語法明智?
這是我所得到的,當我運行代碼:
[[email protected] tmp]# ./envrestore.py -e dev1 dev2 dev3
Namespace(myenv=['dev1', 'dev2', 'dev3'])
Traceback (most recent call last): File "./envrestore.py", line 43, in run_create_snap() File "./envrestore.py", line 36, in run_create_snap for e in myenv: TypeError: 'Namespace' object is not iterable
[[email protected] tmp]#
#!/usr/bin/env python
import pexpect, sys, datetime, argparse, time
from fabric.api import *
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--myenv', nargs='*', type=str)
print parser.parse_args()
array = "vnx.lipsum.com"
seckey = "/opt/Navisphere/blah"
myenv = parser.parse_args()
dbhosts = ['mongo01', 'mysql01']
# !! DO NOT CHANGE IDs !!
lunpnum = "0000000"
mongo_plunid = "3"
mysql_plunid = "4"
def delete_snap(env=myenv, host=dbhosts):
child = pexpect.spawn('naviseccli -secfilepath %s -h %s snap -destroy -id %s-%s-snap' % (seckey, array, host, env))
print child
child.logfile = sys.stdout
child.expect('Are you sure you want to perform this operation\?\(y\/n\):')
child.sendline('n')
def create_snap(env=myenv, host=dbhosts, lunid=''):
print "naviseccli -secfilepath %s -h %s snap -create -res %s -name %s-%s-snap -allowReadWrite yes" % (seckey, array, lunid, host, env)
def run_delete_snap():
for e in myenv:
for h in dbhosts:
delete_snap(env=e, host=h)
def run_create_snap():
for e in myenv:
for h in dbhosts:
if "mysql" in h:
create_snap(env=e, host=h, lunid=mysql_plunid)
elif "mongo" in h:
create_snap(env=e, host=h, lunid=mongo_plunid)
run_create_snap()
非常感謝,這個伎倆。 [[email protected] tmp]#./envrestore.py -e dev1 naviseccli -secfilepath/opt/Navisphere/blah -h vnx.lipsum.com snap -create -res 3 -name mongo01-dev1-snap - allowReadWrite是 naviseccli -secfilepath/opt/Navisphere/blah -h vnx.lipsum.com snap -create -res 4 -name mysql01-dev1-snap -allowReadWrite yes – jed