Anurag-Sharma
Anurag-Sharma

Reputation: 4398

Using subprocess in python 3

I was using the subprocess module to run the shell command in python 3.
Here is my code

import subprocess
filename = "somename.py"  # in practical i'm using a real file, this is just for example
subprocess.call("pep8 %s" % filename, shell=True)) 

The output for different files is just 0 or 1. I am quite new to python 3. Using this in 2.7 gives me the desired output, but here i am not able to figure it out.
This is the output i get in python 2.7 (for a file named - anu.py ) -

anu.py:2:1: W191 indentation contains tabs
anu.py:3:1: W191 indentation contains tabs
anu.py:3:7: E228 missing whitespace around modulo operator
anu.py:4:1: W191 indentation contains tabs
anu.py:5:1: W191 indentation contains tabs
anu.py:6:1: W191 indentation contains tabs
anu.py:7:1: W191 indentation contains tabs
anu.py:7:9: E231 missing whitespace after ','
anu.py:8:1: W191 indentation contains tabs
anu.py:9:1: W191 indentation contains tabs
1

Please help me guys. Thanks

Update:
I tried using subprocess.check_output method,
Here is the ouput i got,

>>> subprocess.check_output(["pep8", "anu.py"])
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "X/subprocess.py", line 584, in check_output
it too will be used internally.  Example:
subprocess.CalledProcessError: Command '['pep8', 'anu.py']' returned non-zero exit status 1

Upvotes: 3

Views: 3204

Answers (1)

dano
dano

Reputation: 94871

subprocess.call only returns the exit code of the process it ran. Normally I'd recommend using subprocess.check_output, which will return the actual output of the subprocess. However, in your particular case, pep8 will return a non-zero exit code in some cases, which will make check_output raise an exception. You can catch the exception and extract the output attribute from it:

try:
    output = subprocess.check_output(['pep8', 'anu.py'])
except subprocess.CalledProcessError as e:
    output = e.output

Or just use subprocess.Popen directly:

p = subprocess.Popen(['pep8', 'anu.py'], stdout=subprocess.PIPE)
(output, _) = p.communicate()

Note that the call behavior hasn't changed between Python 2.x and Python 3.x. The difference in behavior you're seeing might be because you're running Python 2.7 in an interactive prompt, but running the Python 3 version as an actual script. Using subprocess.call in the interactive prompt will still end up printing the output of the call, even though it's not actually being returned by the function.

Upvotes: 7

Related Questions