【问题标题】:Issue with Subprocess and popenSubprocess 和 popen 的问题
【发布时间】:2016-11-08 04:35:52
【问题描述】:

最近,我编写了以下代码来从另一个 python 代码运行 python 文件 'file1.py'。我正在研究树莓派(使用 raspian)

Python 代码:

    import subprocess
    subprocess.Popen(['python','./file1.py'])
    print 'Done'

输出:

    Done

file1.py 没有执行,屏幕上没有其他响应

file1.py

    a=5
    a=a+5
    print(a)

我搜索了同样的问题,但它对我不起作用。请帮忙!

Running multiple Python scripts

【问题讨论】:

  • 你为什么使用subprocess.Popen() 来运行另一个脚本?不能直接导入正常运行吗
  • 嗨@amratansh-gupta,你为什么不在file1.py文件中使用shebang?
  • 如果将subprocess.Popen 替换为subprocess.check_call 会发生什么?

标签: python subprocess


【解决方案1】:

Popen fork 当前进程,这意味着您不会仅通过在执行的脚本中打印来查看其输出。

你需要重定向它的输出:

p = subprocess.Popen(['python','./file1.py'], stdout=subprocess.PIPE)
print(p.stdout.read())

【讨论】:

  • 非常感谢,它正在工作。但是,如果我的 file1.py 需要来自用户的输入值,在这种情况下,我该如何修改它以便能够输入所需的数据?
【解决方案2】:
p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)
print p.communicate()[0]

或

print(p.stdout.read())

Communicate() 将检索最后处理的进程输出,这将有助于查看结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 2021-06-20
    • 1970-01-01
    • 2013-12-09
    • 2017-06-10
    • 1970-01-01
    • 2014-09-13
    相关资源
    最近更新 更多