简体   繁体   中英

Sending arguments to a program that is already open in Python 3

What I am trying to do is better explained here: Sending to the stdin of a program in python3

I am trying to send arguments to a program while it is open eg:

rec.py

import sys
import time

while True:
   print(sys.argv)
   time.sleep(1)

send.py

import subprocess

program = Popen(['python.exe', 'rec.py', 'testArg'])
a = input('input: ')
a.communicate(b)

I want to be able to run send.py and type in my input. Say my input was 'cat', I would want the output to look like this when I run send.py

['rec.py', 'testArg']
['rec.py', 'testArg']
['rec.py', 'testArg']
cat <------- My input
['rec.py', 'testArg', 'cat']
['rec.py', 'testArg', 'cat']
['rec.py', 'testArg', 'cat']
['rec.py', 'testArg', 'cat']

ect..

Am I using the subprocess.Popen.communicate() incorrectly or is it something else?

Please help!

-Thanks

You can't change the command-line arguments after the program has started ie, sys.argv can be changed only from the inside (normally) of the process itself.

Popen.communicate(input=data) can send data to the child process via its standard input (if you pass stdin=PIPE to Popen() ). .communicate() waits for the process to exit before returning and therefore it can be used to send all the input at once.

To send the input incrementally, use process.stdin directly:

#!/usr/bin/env python3
import sys
import time
from subprocess import Popen, PIPE

with Popen([sys.executable, 'child.py'], 
           stdin=PIPE, # redirect process' stdin
           bufsize=1, # line-buffered
           universal_newlines=True # text mode
           ) as process:
    for i in range(10):
        time.sleep(.5)
        print(i, file=process.stdin, flush=True)

where child.py :

#!/usr/bin/env python3
import sys

for line in sys.stdin: # read from the standard input line-by-line
    i = int(line)
    print(i * i) # square

A better option is to import the module and use its functions instead. See Call python script with input with in a python script using subprocess

That's not the way interprocess-communication works. You are mixing command line arguments with the standard input pipe.

This will work:

rec.py:

import sys
import time
arguments = list(sys.argv)

while True:
    print(arguments)
    arguments.append(next(sys.stdin))

send.py

import subprocess
program = subprocess.Popen(['python.exe', 'rec.py', 'testArg'], stdin=subprocess.PIPE)
a = input('input: ')
program.stdin.write(a + '\n')

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