Issue
I was trying to write an automated task with Python3 and using subprocess.call
as I need to run some shell commands as part of the script, but found one of the outputs was not printing in the right order as I expected.
Portion of it:
On Python2:
[root@server101 ~]# cat check_kernel.py
#!/usr/bin/env python
import subprocess
print "Current running kernel version on the system is:\n", subprocess.call(["uname", "-r"])
Output:
[root@server101 ~]# ./check_kernel.py
Current running kernel version on the system is:
3.10.0-1160.45.1.el7.x86_64
0
On Python3:
[root@server101 ~]# cat check_kernel.py
#!/usr/bin/env python3
import subprocess
print ("Current running kernel version on the system is:\n", subprocess.call(["uname", "-r"]))
Output:
[root@server101 ~]# ./check_kernel.py
3.10.0-1160.45.1.el7.x86_64
Current running kernel version on the system is:
0
So what is the real difference there happening with subprocess.call
when working with Python3?.
Am I missing something or I shouldn't be using subprocess.call
with Python3 and changing it to subprocess.run
or subprocess.Popen
is the only way to get subprocess worked with Python3 ?.
Solution
Your subprocess prints the output by itself, and the function returns the return code. The print order could be influenced by Python's output buffering settings.
Just use subprocess.check_output
to get the output that the command would print.
import subprocess, shutil
print ("Current running kernel version on the system is:\n", subprocess.check_output([shutil.which("uname"), "-a"]))
edit
As I imagined, the Python 2 version is
print "Current running kernel version on the system is:\n", subprocess.call(["uname", "-r"])
The Python 2 print statement evaluates and prints each expression in sequence.
The Python 3 print function is just a regular function, so arguments are evaluated first, and the function prints the evaluated values
Since the side effect of invoking uname is to print the uname, it gets printed first, followed by print doing its thing - printing the text and the return value of call
, the zero return code.
Answered By - AKX Answer Checked By - Robin (WPSolving Admin)