如何将包含list的变量作为参数传递给另一个python脚本
我使用下面的脚本将列表变量传递给另一个python脚本。这里我将如何将包含list的变量作为参数传递给另一个python脚本,python,python-3.x,Python,Python 3.x,我使用下面的脚本将列表变量传递给另一个python脚本。这里我将a作为列表变量传递 脚本测试.py: import sys,os a=[1,2,3,4,5] os.system(f"python test2.py '{a}' ") import sys print("inside test4.py") received_list=sys.argv print(received_list) print(sys.argv[0]) print(sys.argv[1]) inside test2
a
作为列表变量传递
脚本测试.py:
import sys,os
a=[1,2,3,4,5]
os.system(f"python test2.py '{a}' ")
import sys
print("inside test4.py")
received_list=sys.argv
print(received_list)
print(sys.argv[0])
print(sys.argv[1])
inside test2.py
['test2.py', "'[1,", '2,', '3,', '4,', "5]'"]
test2.py
'[1,
inside test2.py
['test2.py', '[1,2,3,4,5]']
test2.py
[1,2,3,4,5]
下面的脚本将接收变量并尝试打印传递给test2.py的内容
脚本test2.py:
import sys,os
a=[1,2,3,4,5]
os.system(f"python test2.py '{a}' ")
import sys
print("inside test4.py")
received_list=sys.argv
print(received_list)
print(sys.argv[0])
print(sys.argv[1])
inside test2.py
['test2.py', "'[1,", '2,', '3,', '4,', "5]'"]
test2.py
'[1,
inside test2.py
['test2.py', '[1,2,3,4,5]']
test2.py
[1,2,3,4,5]
我试图获取完整的列表,但我只得到第一个元素,如下面的“[1,
实际输出:
import sys,os
a=[1,2,3,4,5]
os.system(f"python test2.py '{a}' ")
import sys
print("inside test4.py")
received_list=sys.argv
print(received_list)
print(sys.argv[0])
print(sys.argv[1])
inside test2.py
['test2.py', "'[1,", '2,', '3,', '4,', "5]'"]
test2.py
'[1,
inside test2.py
['test2.py', '[1,2,3,4,5]']
test2.py
[1,2,3,4,5]
预期输出:
import sys,os
a=[1,2,3,4,5]
os.system(f"python test2.py '{a}' ")
import sys
print("inside test4.py")
received_list=sys.argv
print(received_list)
print(sys.argv[0])
print(sys.argv[1])
inside test2.py
['test2.py', "'[1,", '2,', '3,', '4,', "5]'"]
test2.py
'[1,
inside test2.py
['test2.py', '[1,2,3,4,5]']
test2.py
[1,2,3,4,5]
如果我显式地传递列表而不是变量,即os.system(f'pythonttest4.py“[1,2,3,4,5]”),我就能够获得预期的输出。
如何通过传递变量来实现这一点。test.py
import sys,os
a=[1,2,3,4,5]
os.system("python test4.py "+",".join(map(str,a)))
test4.py
import sys, ast
print("inside test4.py")
received_list=sys.argv
print(received_list)
print(sys.argv[0])
print(list(ast.literal_eval(sys.argv[1])))
test.py
import sys,os
a=[1,2,3,4,5]
os.system("python test4.py "+",".join(map(str,a)))
test4.py
import sys, ast
print("inside test4.py")
received_list=sys.argv
print(received_list)
print(sys.argv[0])
print(list(ast.literal_eval(sys.argv[1])))
我认为os.system(f“pythonttest2.py{str(a)}”)
就可以了您离开Python专区,进入shell环境。shell不知道Python列表,只看到5个用空格分隔的参数。您应该查看模块并使用import
,这不是我们使用其他Python脚本的方式。我认为os.system(f“Python test2.py{str(a)}”)
就可以了。当您调用os.system()您离开Python专区,进入shell环境。shell不知道Python列表,只看到5个用空格分隔的参数。您应该查看模块并使用import
,这不是我们使用其他Python脚本的方式。您可以使用ast.literal\u eval()代替eval,而不是使用ast.literal\u eval()