Execute command from python

code

import subprocess
import sys


def exec_cmd(cmd):
    #Delete any spaces before or after the cmd string->Divide by space and make a list
    cmd_split = cmd.strip().split()
    #Get standard output with stdout settings
    cp = subprocess.run(cmd_split, stdout=subprocess.PIPE)
    # cp = subprocess.check_output(cmd_split)
    if cp.returncode != 0:
        print(f'{cmd_split[0]} faild.', file=sys.stderr)
        sys.exit(1)
    #Returns if there is standard output
    if cp.stdout is not None:
        return cp.stdout

Run

Pass the command as it is as a string

cmd = 'touch file.py'
exec_cmd(cmd)

For lists, join () separated by spaces

files = ['file1.py', 'file2.py', 'file3.py', 'file4.py', 'file5.py']
files_sep_space = ' '.join(files)
cmd = f'touch {files_sep_space}'
exec_cmd(cmd)

Recommended Posts

Execute command from Python
Execute command from python
[Python] Execute unix command (subprocess)
Execute external command in python
Load and execute command from yml in python
Execute Python script from batch file
Execute Python code from C # GUI
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
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
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)
Twitter post from command line
OCR from PDF in Python
Run illustrator script from python
Use MySQL from Anaconda (python)
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
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!
Use e-Stat API from Python
Register redmine issue from Python
Get information such as GPU usage from Python (nvidia-smi command)
I made you to execute a command from a web browser