How do I execute a command from python and receive the result? If you can execute commands directly from the script, you can save the trouble of executing commands to process the results after the script execution is completed.
There are several ways to execute commands from python, but this time I will explain how to use the subprocess module.
call Pass the command you want to execute in list format and the process will be executed. If successful, 0 is returned.
In [1]: import subprocess
In [2]: subprocess.call(["ls", "-la"])
Out[2]: 0
Setting shell = True
is convenient because you can execute the command as follows.
In [3]: subprocess.call("ls -la", shell=True)
Out[3]: 0
check_call
If you pass a command that does not exist in call
, you will only get the error command not found
, but if you use check_call
you can throw an exception called CalledProcessError
.
I got an exception called CalledProcessError
.
In [5]: subprocess.check_call("lddd", shell=True)
/bin/sh: lddd: command not found
---------------------------------------------------------------------------
CalledProcessError Traceback (most recent call last)
<ipython-input-5-00471ece15fa> in <module>()
----> 1 subprocess.check_call("lddd", shell=True)
/Users/SoichiroMurakami/.pyenv/versions/anaconda-2.4.0/lib/python2.7/subprocess.pyc in check_call(*popenargs, **kwargs)
539 if cmd is None:
540 cmd = popenargs[0]
--> 541 raise CalledProcessError(retcode, cmd)
542 return 0
543
CalledProcessError: Command 'lddd' returned non-zero exit status 127
It just returns command not found
.
In [6]: subprocess.call("lddd", shell=True)
/bin/sh: lddd: command not found
Out[6]: 127
check_output
You can execute a command with arguments and get the output as a string. This is convenient when you want to use the command execution result in a script.
In [9]: cal_output = subprocess.check_output("cal", shell=True)
In [10]: print cal_output
November 2016
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
This is a supplement for command execution methods other than the subprocess module. There seem to be two methods, but they are not currently recommended.
command
)command
)Recommended Posts