Seite 1 von 1

Interaktion mit der Bash

Verfasst: Donnerstag 13. Oktober 2016, 14:11
von schuster.stef
https://pymotw.com/2/subprocess/ beschreibt:

Code: Alles auswählen

import subprocess

print 'One line at a time:'
proc = subprocess.Popen('python repeater.py', 
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        )
for i in range(10):
    proc.stdin.write('%d\n' % i)
    output = proc.stdout.readline()
    print output.rstrip()
remainder = proc.communicate()[0]
print remainder

print
print 'All output at once:'
proc = subprocess.Popen('python repeater.py', 
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        )
for i in range(10):
    proc.stdin.write('%d\n' % i)

output = proc.communicate()[0]
print output
Leichteste Umwandlung in:

Code: Alles auswählen

#!/usr/bin/python
import subprocess

print 'One line at a time:'
proc = subprocess.Popen('echo ju', 
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        )
for i in range(10):
    proc.stdin.write('%d\n' % i)
    output = proc.stdout.readline()
    print output.rstrip()
remainder = proc.communicate()[0]
print remainder

print
print 'All output at once:'
proc = subprocess.Popen('echo ju', 
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        )
for i in range(10):
    proc.stdin.write('%d\n' % i)

output = proc.communicate()[0]
print output
Bei mir führt das zu:

Code: Alles auswählen

One line at a time:
ju
Traceback (most recent call last):
  File "abc.py", line 11, in <module>
    proc.stdin.write('%d\n' % i)
IOError: [Errno 32] Broken pipe


------------------
(program exited with code: 1)
Press return to continue



Warum führt das zum Fehler?

Re: Interaktion mit der Bash

Verfasst: Donnerstag 13. Oktober 2016, 14:40
von BlackJack
@schuster.stef: Weil ``echo ju`` wirklich ganz schnell geht und damit am anderen Ende von `proc.stdin` kein Empfänger mehr ist der auf die Eingaben wartet.

Ob das wirklich Interaktion mit einer Bash ist/wird hängt übrigens davon ab welche Systemshell da gestartet wird. Nur das Du Dich nicht wunderst wenn da Bash-spezifisches nicht funktioniert weil auf vielen Linux-Distributionen die Dash als Systemshell läuft. Wenn man da einen spezielle Shell haben möchte, dann sollte man die explizit starten. Dann braucht man ``shell=True`` auch nicht, weshalb das erste Beispiel auch nicht so gut ist, da dort die zusätzlich zwischengeschaltete Shell keinen Sinn macht.