繁体   English   中英

将参数/字符串传递到已经运行的进程中-Python 2.7

[英]Passing arguments/strings into already running process - Python 2.7

我在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文件,并一次又一次打印所有输入内容。
问题是我不想打开新流程。 应该只有一个过程。 可能吗?

把你的手给我 :)

通过使用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)

您需要在循环外部打开该过程才能起作用。 如果您要检查“ 保持子进程处于活动状态并继续向其发送命令” ,这里也解决了类似的问题 蟒蛇

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM