Execute command from Python

Introduction

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.

subprocess module

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.

When executed with check_call

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

When executed by call

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

Other methods

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.

Recommended Posts

Execute command from Python
Execute command from python
[Python] Execute unix command (subprocess)
Load and execute command from yml in python
Execute Python script from batch file
Execute Python code from C # GUI
sql from python
MeCab from Python
Call a command from Python (Windows version)
[Note] Execute Python code from Excel (xlwings)
Use thingsspeak from python
Touch MySQL from Python 3
Operate Filemaker from Python
Use fluentd from python
Access bitcoind from python
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Python from or import
Automatically execute python file
Use MySQL from Python
Run python from excel
Install python from source
Operate neutron from Python!
Use MySQL from Python
[Node-RED] Execute Python on Anaconda virtual environment from Node-RED [Anaconda] [Python]
Operate LXC from Python
Basic Python command memo
Manipulate riak from python
Force Python from Fortran
Use BigQuery from python.
[Python] Read From Stdin
Use mecab-ipadic-neologd from python
Execute Python function from Powershell (how to pass arguments)
How to execute a command using subprocess in Python
Flatten using Python yield from
Call CPLEX from Python (DO cplex)
Deep Python learned from DEAP
Post from Python to Slack
Grammar features added from Python3.6
Cheating from PHP to Python
Make MeCab available from Python3
Information obtained from tweet_id (Python)
OCR from PDF in Python
Run illustrator script from python
Use MySQL from Anaconda (python)
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
Study from Python Hour4: Object-oriented ②
Query Athena from Lambda Python
Access Oracle DB from Python
Study from Python Hour3: Functions
Start / stop GCE from python
Stop Omxplayer from Python code
Run unix command on python
Switch from python2.7 to python3.6 (centos7)
Connect to sqlite from python
Install pyenv from Homebrew, install Python from pyenv
Study from Python Hour4: Object-oriented ①
Python naming convention (from PEP8)
External command execution in Python
Python eval can execute statements.
With skype, notify with skype from python!