简体   繁体   English

从另一个调用 Python 脚本并将 List(sys.argv) 作为参数传递

[英]Calling Python script from another and passing List(sys.argv) as argument

test1.py is the main script calling another script test2.py by passing the same argument list that has been passed to test1.py. test1.py 是主脚本,通过传递与 test1.py 相同的参数列表来调用另一个脚本 test2.py。 I have done following but it reads the sys.argv list as string and parse into multiple arguments and also includes unnecessary [ and ,我已经完成了以下操作,但它将 sys.argv 列表读取为字符串并解析为多个参数,还包括不必要的 [ 和 ,

test1.py
import os
import sys

argList=sys.argv[1:]

os.system('python another/location/test2.py %s'%(argList))

test2.py

import sys
print(sys.argv[1:])

Call test1.py
python test1.py -a -b -c
output: ['[-a,' ,'-b,', '-c]' ]

Please post if there is a better opti如果有更好的选择请发帖

Use使用

os.system('python another/location/test2.py %s' % ' '.join(argList))

if the arguments will contain no spaces themselves.如果参数本身不包含空格。

The second program will output第二个程序将输出

['-a', '-b', '-c']

If your arguments can contain spaces, it might be best to quote them.如果您的参数可以包含空格,最好引用它们。 Use ' '.join("'%s'" % arg.replace("'", "\\\\'") for arg in ArgList)使用' '.join("'%s'" % arg.replace("'", "\\\\'") for arg in ArgList)

in the case if you need to exit test1.py just after calling test2.py如果您需要在调用 test2.py 后立即退出 test1.py

import subprocess
subprocess.Popen( ('python', 'another/location/test2.py') + tuple( sys.argv[1:]) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM