fajin yu
fajin yu

Reputation: 153

Got different result when using subprocess.popen and subprocess.run

When I execute below program, it list file correctly.

import subprocess


foo = subprocess.run("ls /home/my_home", 
                     shell=True, 
                     executable="/bin/bash", 
                     stdout=subprocess.PIPE, 
                     stdin=subprocess.PIPE, 
                     stderr=subprocess.PIPE)
my_std_out = foo.stdout.decode("utf-8")

But when execute below program, there is nothing in stdout.

import subprocess


foo = subprocess.Popen(["ls /home/my_home"], 
                       shell=True, 
                       executable="/bin/bash", 
                       stdout=subprocess.PIPE, 
                       stdin=subprocess.PIPE, 
                       stderr=subprocess.PIPE)
my_std_out = foo.stdout.read().decode("utf-8")

I wonder is there anything wrong with my second part program?
Thankyou in advance!

Upvotes: 0

Views: 311

Answers (2)

joker57
joker57

Reputation: 150

From python docs: "communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes." Therefore, if you'd like to get output via Popen, you have to unpack the retruned tuple from communicate() like this:

out, err = foo.communicate()
In [150]: out
Out[150]: b''
In [151]: err
Out[151]: b"ls: cannot access '/home/my_home': No such file or directory\n"

Upvotes: 2

user13824946
user13824946

Reputation:

I think the bash command and the path should be placed between quotes each when you use brackets like the following

import subprocess foo = subprocess.Popen(["ls", "/home/my_home"], shell=True, executable=/bin/bash, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) my_std_out = foo.stdout.read().decode("utf-8")

Upvotes: 0

Related Questions