如何获取子进程check_output以使用 sys.argv 调用脚本?



我正在尝试让一个sys.argv与脚本名称一起在调用另一个脚本并返回输出的子进程中传递。 我在尝试执行程序时收到几个不同的错误。 一个是TypeError:预期的str,bytes或os。路径类对象,而不是整数。 我用下面列出的代码得到这个。

当我尝试将 mytext 转换为字符串时,str(15) 出现此错误:命令'('python/users/cmbp/p4e/helloworld_final2.py', '15')' 返回非零退出状态 1。

当我尝试在没有 sys.argv 的情况下运行调用第二个脚本 (helloworld_final2.py) 的子进程时,它工作正常。

此外,当我使用 sys.argv 从命令行调用helloworld_final2.py文件时,该文件运行良好。 例如,python/users/cmbp/p4e/helloworld_final2.py 15 将在 print 语句中返回数字 15。 这在脚本subprocess_test.py不起作用。

以下是带有子流程的脚本 (subprocess_test.py):

import subprocess
mytext = 15
cmd = "python /users/cmbp/p4e/helloworld_final.py", mytext
output = subprocess.check_output(cmd, shell=True)
print(output.decode('utf-8'))

这是我尝试调用的脚本(helloworld_final2.py):

import sys
def cooz():
print (sys.argv[1])
print ('hello world!')
def tooz():
print ("here is another line")
print ("stuff")
tooz()
cooz()

任何帮助将不胜感激!

您可以通过将cmd格式化为列表来更改它。

cmd = ["python",  "/users/cmbp/p4e/helloworld_final.py", str(mytext)]

然后

output = subprocess.check_output(cmd)
print(output.decode('utf-8'))

应该工作。