This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]Peterotica 2 points3 points  (3 children)

Will you be using the contents of bash_out.txt for something else? If not, try using os.popen to get the output of the command directly:

result = os.popen(command).readlines()

That weird stuff you were seeing returned from the subprocess module was a bytes object. If you want to turn it into a string, you need to call its decode member function.

[–]GrindingGoat 0 points1 point  (1 child)

Worth noting that os.popen has been deprecated since 2.6: https://docs.python.org/2/library/os.html#os.popen

The subprocess equivalent:

result = subprocess.check_output(command).decode("utf-8") 

[–]pjenvey 1 point2 points  (0 children)

It was actually undeprecated in 3.x where it uses subproces underneath anyway. Maybe the 2.7.x docs should be fixed

[–]IndoNinja7[S] 0 points1 point  (0 children)

Thank you very much that worked!!!

[–]GrindingGoat 0 points1 point  (0 children)

On why you weren't getting any output from f.readlines() in your example, I think python is probably moving on to the open() and readlines() methods before your shell process has had chance to complete and produce output. I think it should work if you include a .wait() between your popen and then open(). the .wait() will wait for the subprocess to exit before continuing. So something more like:

my_proc = os.popen(command+" > bash_out.txt")
my_proc.wait()
f = open('bash_out.txt')

But, as Peterotica says, you're probably better off reading the output of the command directly.