Shang Wang
Shang Wang

Reputation: 25539

Use python to run shell script with Popen behaves differently in python command line and actual program

I have a shell script that I want to call from a python program, but doesn't work at all with following code(Popen already imported):

bf_dir = '/home/wireless'
bf_path = os.path.join(bf_dir, 'airdispatch.sh')
sh = Popen("sudo " + bf_path, shell=True)
print sh.communicate()

Ideally, the script will generate output files, but by executing above code, those files don't appear, and the "print" result is [None, None]. My guess is that the "Popen" somehow doesn't get executed at all, or might be that I made a mistake here. So I run above code in python command line, but it turns out that everything works fine. How can that be possible? Please help, thanks.

Upvotes: 2

Views: 2709

Answers (2)

deinonychusaur
deinonychusaur

Reputation: 7304

Using shell=True and invoking sudo sounds risky (look here), I'd rather use Popen with a list and not as a text string.

sh = Popen(['sudo', bf_path], shell=False, stdout=PIPE, stderr=PIPE)

Upvotes: 1

jdi
jdi

Reputation: 92569

The reason you are not getting any output from the command is because you have not told the subprocess to open pipes for communication...

from subprocess import Popen, PIPE

sh = Popen("sudo %s" % bf_path, shell=True, stdout=PIPE, stderr=PIPE)

Now communicate will return the output of both stdout and stderr. Also, its possible that the sudo might cause you problems if it requires a password input.

Upvotes: 3

Related Questions