简体   繁体   中英

Passing arguments/strings into already running process - Python 2.7

I have two scripts in Python.

sub.py code:

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:

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...
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 . Check my answer over here. It solves a similar problem

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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