【问题标题】:Return value of child_process in terminal终端中 child_process 的返回值
【发布时间】:2020-07-14 23:13:01
【问题描述】:

如何返回一个python子进程的值,我通过main.py通过以下代码开始:

subprocess.check_output(['lxterminal -e  python3 rfid_input.py'], stdin=subprocess.PIPE, shell=True, close_fds=True)

父进程:

import sys, subprocess
value = subprocess.check_output(['lxterminal -e  python3 rfid_input.py'], stdin=subprocess.PIPE, shell=True, close_fds=True)
print(value)

子进程包含一个简单的x=input(),如下所示:

import sys
x=input()
sys.stdout.write(x)

但我仍然没有收到任何其他内容作为空的b''。

我还通过subprocess.Popen 和.wait() 和.communicate() 尝试过,但没有成功。

如果您对如何获取 lxterminal 输入的值有任何其他想法,请告诉我。

【问题讨论】:

    标签: python subprocess stdout python-3.7


    【解决方案1】:

    为了向标准输入传递数据,您的设置通常如下所示

    import subprocess
    
    stdin = b"THE DATA YOU PASS"
    terminal = subprocess.Popen(["lxterminal", "-e", "python3", "rfid_input.py"],
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
    stdout, stderr = terminal.communicate(stdin)
    

    当您不带参数调用.communicate 时,它通常会传递空字节,这可能就是这里发生的情况。

    模板示例:

    家长:

    import subprocess
    
    stdin = b"THE DATA YOU PASS"
    terminal = subprocess.Popen(["python3", "stackoverflow_child.py"],
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
    stdout, stderr = terminal.communicate(stdin)
    print(stdout.decode("utf-8"), stderr.decode("utf-8"))
    

    名字为stackoverflow_child.py的孩子:

    import sys
    x=input()
    sys.stdout.write(x * 2)  # so you can see the child was called
    

    如果你不想处理字节,你也可以将encoding="utf-8"传递给Popen,然后你可以将stdin作为字符串传递并接收stdout和stderr作为字符串。

    【讨论】:

      猜你喜欢
      • 2014-06-03
      • 2021-03-29
      • 2020-04-28
      • 2011-11-12
      • 2019-12-05
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多