【问题标题】:How to get a subprocess check_output to call a script with sys.argv?如何让子进程 check_output 使用 sys.argv 调用脚本?
【发布时间】:2018-01-08 04:09:28
【问题描述】:

我正在尝试在调用另一个脚本并返回输出的子进程中将 sys.argv 与脚本名称一起传递。我在尝试执行程序时收到几个不同的错误。一种是 TypeError: expected str, bytes or os.PathLike object, not int。我用下面列出的代码得到了这个。

当我尝试将 mytext 转换为字符串时,str(15) 出现此错误:Command '('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 将在打印语句中返回数字 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()

任何帮助将不胜感激!

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

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

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

    然后

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

    应该工作。

    【讨论】:

      猜你喜欢
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      相关资源
      最近更新 更多