Python - subprocesses and python shell

I am trying to lay out on a non-python subprocess and allow it to inherit stdin and stdout from python. - I am using subprocess.Popen

This will probably work if I call from the console, but it definitely does not work when I use the python shell

(By the way, I'm using IDLE)

Is there a way to convince python to allow the non-python subprocess to print its stdout to the python shell?

+5
source share
2 answers

This works both from the script and from the interactive interpreter, but not from IDLE:

subprocess.Popen(whatever, stdin=sys.stdout, stdout=sys.stdin)

, IDLE sys.stdin sys.stdout subprocess.Popen. ( IDLE) , fileno, Unix- fileno stdin stdout , Windows, , .

+6

Taymon , IDLE stdin/stdout - - , , /. , Windows IDLE pythonw.exe, win32.

, , ( ) . Windows IDLE . stdout . , , , readline , . ( Python -u), Unix , stdbuf.

test1.py

import sys
import subprocess

def test(cmd):
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, 
                         stderr=subprocess.PIPE)
    it = iter(p.stdout.readline, b'')
    for line in it:
        print(line.rstrip().decode('ascii'))

print('Testing buffered subprocess...')
test([sys.executable, 'test2.py'])

print('\nTesting unbuffered subprocess...')
#-u: unbuffered binary stdout and stderr
test([sys.executable, '-u', 'test2.py']) 

test2.py:

import time

for i in range(5):
    print(i)
    time.sleep(1)

IDLE : , .

Testing buffered subprocess...
0
1
2
3
4

Testing unbuffered subprocess...
0
1
2
3
4
+4

All Articles