【问题标题】:Passing arguments/strings into already running process - Python 2.7将参数/字符串传递给已经运行的进程 - Python 2.7
【发布时间】:2016-06-29 03:38:42
【问题描述】:

我有两个 Python 脚本。

sub.py 代码:

import time
import subprocess as sub

while 1:
  value=input("Input some text or number") # it is example, and I don't care about if it is number-input or text-raw_input, just input something
  proces=sub.Popen(['sudo', 'python', '/home/pi/second.py'],stdin=sub.PIPE)
  proces.stdin.write(value)

second.py 代码:

import sys
while 1:
 from_sub=sys.stdin()#or sys.stdout() I dont remember...
 list_args.append(from_sub) # I dont know if syntax is ok, but it doesn't matter
 for i in list_arg:
    print i

首先我执行 sub.py,然后输入一些内容,然后 second.py 文件将执行并打印我输入的所有内容,并一次又一次地打印...
问题是我不想打开新进程。应该只有一个过程。可能吗?

把手给我:)

【问题讨论】:

  • 最好使用python命名约定,while True而不是while 1
  • 在 Python 2.x 中,使用 while 1 而不是 while True 会更快,因为 True 不是关键字而是需要解释的全局变量,所以如果您需要最大速度 @ 987654328@ 击败 while True。在 Python 3.x 中,True|False 成为关键字,因此生成的字节码是等效的。
  • 您的代码不是有效的 Python,indetion 使用了不同数量的空格。

标签: python subprocess popen


【解决方案1】:

这个问题可以通过Pexpect来解决。在这里检查我的答案。它解决了类似的问题

https://stackoverflow.com/a/35864170/5134525.

另一种方法是使用子进程模块中的 Popen 并将 stdin 和 stdout 设置为管道。稍微修改你的代码可以给你想要的结果

from subprocess import Popen, PIPE
#part which should be outside loop
args = ['sudo', 'python', '/home/pi/second.py']
process = Popen(args, stdin=PIPE, stdout=PIPE)
while True:
    value=input("Input some text or number")
    process.stdin.write(value)

您需要在循环外打开进程才能使其正常工作。如果您想检查 Keep a subprocess alive and keep giving it commands? Python

如果子进程在第一次迭代后退出并关闭所有管道,这种方法将导致错误。您需要以某种方式阻止子进程以接受更多输入。这可以通过使用线程或使用第一个选项来完成,即 Pexpect

【讨论】:

  • [italic ' process.stdin.write(value) '] 不能在循环内... 错误 22。
  • 但是看,子进程无法完成,因为有while 1:这意味着它始终为真,并且应该在执行一次后始终运行进程。我说的对吗?
  • 您能否将完整的代码连同您提供的输入一起包含在内?
  • 据我所知;一旦遇到文件结尾,即第一次读取所有参数;管道将关闭。这就是管道的设计方式。执行此操作的其他方法是使用线程或套接字。 Pexpect 是一个不错的选择
猜你喜欢
  • 1970-01-01
  • 2019-03-26
  • 1970-01-01
  • 2011-05-31
  • 2015-02-12
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多