0

I am quite new in 'subprocess' function and wanna to read the output of the command run within python code.

It seems that no problem arose when I line by line ran my code unter python, but when I ran it in bash by typing 'python test.py' (test.py is where my code was packed) it ended up with only b'' and results from 'head' command however were not showed.

import subprocess
pro = subprocess.Popen("sed 's/A/N/g *.txt | head Quelle1.txt'", shell=True,stdout=subprocess.PIPE)
content = pro.stdout.readlines()
for line in content:
    print(list)

any help would be appreciated!!!

citron
  • 85
  • 8
  • After you ran it the first time, the `.txt` content has already been replaced, so on the second run there is nothing more to do would be my guess. – xjcl Mar 02 '22 at 16:12

1 Answers1

0

You see empty output because process has been started in a new process but probably haven't finished yet (subprocess.Popen). When you do everything line by line - you paste commands slower than they get executed.

For a better way - see a solution here

The idea is to wrap in "with" construction

with subprocess.Popen(...) as p:
  pass # your code here
Alexander B.
  • 626
  • 6
  • 21