Python 如何将列表和其他值作为命令行参数传递?
我想向python脚本传递4个参数,其中一个必须是列表。即使它只包含1个元素 争论的顺序无关紧要Python 如何将列表和其他值作为命令行参数传递?,python,python-2.7,Python,Python 2.7,我想向python脚本传递4个参数,其中一个必须是列表。即使它只包含1个元素 争论的顺序无关紧要 import sys print sys.argv one = sys.argv[1] two = sys.argv[2] three = sys.argv[3] four = sys.argv[4] print "one: " + one print "two: " + two print "three: "+ three
import sys
print sys.argv
one = sys.argv[1]
two = sys.argv[2]
three = sys.argv[3]
four = sys.argv[4]
print "one: " + one
print "two: " + two
print "three: "+ three
print "four: " + four
这就是我所说的
python myScript.py name file setting ['listItem1']
其中第四项是包含一个元素的列表。然而,当我打印它时,我看到
four: [listItem1]
我想看看
four: ['listItem1']
你需要避开引用语
python myScript.py name file setting [\'listItem1\']
也许更好的方法是像这样调用脚本
python myScript.py name file setting listItem1 ...
然后使用切片:
four = sys.argv[4:]
这使得python语法不在shell中,这很难看,并且在shell中使用特殊字符以后可能会导致更多问题
更好的方法是使用模块实现适当的CLI 节目:
import sys, ast, getopt, types
def main(argv):
arg_dict={}
switches={'li':list,'di':dict,'tu':tuple}
singles=''.join([x[0]+':' for x in switches])
long_form=[x+'=' for x in switches]
d={x[0]+':':'--'+x for x in switches}
try:
opts, args = getopt.getopt(argv, singles, long_form)
except getopt.GetoptError:
print "bad arg"
sys.exit(2)
for opt, arg in opts:
if opt[1]+':' in d: o=d[opt[1]+':'][2:]
elif opt in d.values(): o=opt[2:]
else: o =''
print opt, arg,o
if o and arg:
arg_dict[o]=ast.literal_eval(arg)
if not o or not isinstance(arg_dict[o], switches[o]):
print opt, arg, " Error: bad arg"
sys.exit(2)
for e in arg_dict:
print e, arg_dict[e], type(arg_dict[e])
if __name__ == '__main__':
main(sys.argv[1:])
python py.py --l='[1,2,3,[1,2,3]]' -d "{1:'one',2:'two',3:'three'}" --tu='(1,2,3)'
args: ['--l=[1,2,3,[1,2,3]]', '-d', "{1:'one',2:'two',3:'three'}", '--tu=(1,2,3)']
tu (1, 2, 3) <type 'tuple'>
di {1: 'one', 2: 'two', 3: 'three'} <type 'dict'>
li [1, 2, 3, [1, 2, 3]] <type 'list'>
命令行:
import sys, ast, getopt, types
def main(argv):
arg_dict={}
switches={'li':list,'di':dict,'tu':tuple}
singles=''.join([x[0]+':' for x in switches])
long_form=[x+'=' for x in switches]
d={x[0]+':':'--'+x for x in switches}
try:
opts, args = getopt.getopt(argv, singles, long_form)
except getopt.GetoptError:
print "bad arg"
sys.exit(2)
for opt, arg in opts:
if opt[1]+':' in d: o=d[opt[1]+':'][2:]
elif opt in d.values(): o=opt[2:]
else: o =''
print opt, arg,o
if o and arg:
arg_dict[o]=ast.literal_eval(arg)
if not o or not isinstance(arg_dict[o], switches[o]):
print opt, arg, " Error: bad arg"
sys.exit(2)
for e in arg_dict:
print e, arg_dict[e], type(arg_dict[e])
if __name__ == '__main__':
main(sys.argv[1:])
python py.py --l='[1,2,3,[1,2,3]]' -d "{1:'one',2:'two',3:'three'}" --tu='(1,2,3)'
args: ['--l=[1,2,3,[1,2,3]]', '-d', "{1:'one',2:'two',3:'three'}", '--tu=(1,2,3)']
tu (1, 2, 3) <type 'tuple'>
di {1: 'one', 2: 'two', 3: 'three'} <type 'dict'>
li [1, 2, 3, [1, 2, 3]] <type 'list'>
输出:
import sys, ast, getopt, types
def main(argv):
arg_dict={}
switches={'li':list,'di':dict,'tu':tuple}
singles=''.join([x[0]+':' for x in switches])
long_form=[x+'=' for x in switches]
d={x[0]+':':'--'+x for x in switches}
try:
opts, args = getopt.getopt(argv, singles, long_form)
except getopt.GetoptError:
print "bad arg"
sys.exit(2)
for opt, arg in opts:
if opt[1]+':' in d: o=d[opt[1]+':'][2:]
elif opt in d.values(): o=opt[2:]
else: o =''
print opt, arg,o
if o and arg:
arg_dict[o]=ast.literal_eval(arg)
if not o or not isinstance(arg_dict[o], switches[o]):
print opt, arg, " Error: bad arg"
sys.exit(2)
for e in arg_dict:
print e, arg_dict[e], type(arg_dict[e])
if __name__ == '__main__':
main(sys.argv[1:])
python py.py --l='[1,2,3,[1,2,3]]' -d "{1:'one',2:'two',3:'three'}" --tu='(1,2,3)'
args: ['--l=[1,2,3,[1,2,3]]', '-d', "{1:'one',2:'two',3:'three'}", '--tu=(1,2,3)']
tu (1, 2, 3) <type 'tuple'>
di {1: 'one', 2: 'two', 3: 'three'} <type 'dict'>
li [1, 2, 3, [1, 2, 3]] <type 'list'>
args:['-l=[1,2,3[1,2,3]],'-d',“{1:'1',2:'2',3:'3'},'-tu=(1,2,3)]
图(1,2,3)
di{1:'一',2:'二',3:'三'}
李[1,2,3,1,2,3]]
此代码段将使用短或长的命令切换,如-l
或--li=
,并将切换后的文本解析为Python数据结构,如列表、元组或dict。解析后的数据结构最终包含在带有长格式切换键的字典中
使用相对安全。它只能解析python数据定义 正如PersonArtPhoto所指出的,您需要避开qutoation标记,以防止shell本身使用它们 在程序中,您将得到一个类似于列表的字符串,这不是您想要的
import sys
four = sys.argv[4]
print four[2]
显示
这个'f'
来自索引“['first','second']”
,因为它只是一个字符串
让python解释这一点的一种方法是
eval
,但它非常不受欢迎,因为它非常不安全eval
将字符串解释为代码,因此不应在用户输入时使用它,因为用户可以输入任何内容,python将执行它
import sys
four = eval(sys.argv[4])
print four[1]
显示
相反,我建议采取更安全的方法。使用命令行标志表示您正在发送参数列表
import sys
# make sure the --args flag was passed
if '--args' not in sys.argv:
print >> sys.stderr, 'Please pass the "--args" flag followed by a list of'\
' arguments'
sys.exit(1) #terminate execution if it wasn't
four = sys.argv[sys.argv.index('--args')+1:] # everything passed after --args
print four
显示
如果您知道在您的列表之前总是有三个参数,那么您可以简单地使用一个切片
import sys
one, two, three = sys.argv[1:4] # grab indicies 1, 2, and 3
four = sys.argv[4:]
print one
print two
print three
print four
显示
我希望您不打算
eval
最后一个参数…变量four
不是一个列表,它是一个包含值'[listItem1]'
的字符串。我们有optparse、argparse模块…您可能想添加原因。(…因为shell正在解释这些…)它总是一个字符串。贝壳给你一根绳子。事实上,它是一个带括号的字符串,并不意味着它是一个列表。该示例只传递没有额外值的列表。主要接受三份名单吗?还是一个列表?@Siecje:参与这个程序,并以您正在执行的前三个位置参数的方式进行集成是很简单的。只需使用sys.argv[4://code>调用函数,然后从那里解析。。。