kumarprd
kumarprd

Reputation: 936

python subprocess is working in interactive mode but in not script

In windows I have to execute a command like below:

process = subprocess.Popen([r'C:\Program Files (x86)\xxx\xxx.exe', '-n', '@iseasn2a7.sd.xxxx.com:3944#dc', '-d', r'D:\test\file.txt'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
process.communicate()

This works fine in python interactive mode, but not at all executing from the python script.

What may be the issue ?

Upvotes: 1

Views: 1220

Answers (1)

falsetru
falsetru

Reputation: 368894

Popen.communicate itself does not print anything, but it returns the stdout, stderr output. Beside that because the code specified stdout=PIPE, stderr=... when it create Popen, it catch the outputs (does not let the sub-process print output directly to the stdout of the parent process)

You need to print the return value manually:

process = ....
output, error = process.communicate()
print output

If you don't want that, don't catch stdout output by omit stdout=PIPE, stderr=....

Then, you don't need to use communicate, but just wait:

process = subprocess.Popen([...], shell=True)
process.wait()

Or, you can use subprocess.call which both execute sub-process and wait its termination:

subprocess.call([...], shell=True)

Upvotes: 1

Related Questions