简体   繁体   English

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

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

I have two scripts in Python. 我在Python中有两个脚本。

sub.py code: 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 code: 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

First I execute sub.py, and I input something, then second.py file will execute and printing everything what I inputed and again and again... 首先,我执行sub.py,然后输入内容,然后执行second.py文件,并一次又一次打印所有输入内容。
The thing is I don't want to open new process. 问题是我不想打开新流程。 There should be only one process. 应该只有一个过程。 Is it possible? 可能吗?

Give me your hand :) 把你的手给我 :)

This problem can be solved by using Pexpect . 通过使用Pexpect可以解决此问题。 Check my answer over here. 在这里检查我的答案。 It solves a similar problem 它解决了类似的问题

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

Another way to do that is to use Popen from subprocess module and setting stdin and stdout as pipe. 另一种方法是使用子进程模块中的Popen并将stdin和stdout设置为管道。 Modifying your code a tad bit can give you the desired results 一点点修改代码即可获得所需的结果

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)

You need to open the process outside the loop for this to work. 您需要在循环外部打开该过程才能起作用。 A similar issue is addressed here in case you want to check that Keep a subprocess alive and keep giving it commands? 如果您要检查“ 保持子进程处于活动状态并继续向其发送命令” ,这里也解决了类似的问题 Python 蟒蛇

This approach will lead to error if child process quits after first iteration and close all the pipes. 如果子进程在第一次迭代后退出并关闭所有管道,则此方法将导致错误。 You somehow need to block the child process to accept more input. 您需要以某种方式阻止子进程以接受更多输入。 This you can do by either using threads or by using the first option ie Pexpect 您可以通过使用线程或使用第一个选项(即Pexpect)来执行此操作

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

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