There are many ways to handle Linux commands from Python, but the best way is to use the Popen class
, which can handle standard output and standard error output structurally.
Function name | Classification | Mold |
---|---|---|
Popen().stdout.readline() | Standard output Only one line is output from the result | str |
Popen().stdout.readlines() | Standard output Output all results as an array | list[str] |
Popen().stderr.readline() | Standard error output Only one line is output from the result | str |
Popen().stderr.readlines() | Standard error output Output all results as an array | list[str] |
output.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from subprocess import PIPE, Popen
def cmdline(command):
"""
Execute a command. shell=If True, execute via the shell.
:param command: str
:return: Popen
"""
return Popen(
args=command,
stdout=PIPE,
stderr=PIPE,
shell=True
)
#Standard output
print 'Standard output:' + cmdline('date').stdout.readline()
#Standard error output
print 'Standard error output: ' + cmdline('echo 2015|xargs wc -l').stderr.readline()
Execution result
>>> python output.py
Standard output:Monday, December 7, 2015 18:47:09 JST
Standard error output: wc: 2015: open: No such file or directory
git.py
#print the latest commit hash of git
print cmdline('git log --oneline').stdout.readline()
#Print the latest commit hash from another repository
print cmdline('cd ~/pypi/cf_recommender/ && git log --oneline').stdout.readline()
Execution result
>>> python git.py
6a2ae0a xlsx update by automatic
a2febc4 update readme
chat.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from subprocess import PIPE, Popen
def cmdline(command):
"""
Execute a command
:param command: str
:return: Popen
"""
return Popen(
args=command,
stdout=PIPE,
stderr=PIPE,
shell=True
)
def chat(message):
#Dummy implementation
print 'ERROR:' + message
#Notify the error content by chat when standard error is output
cmd = [
'python manage.py test_json',
'python manage.py test_battle',
]
#Command execution prefix, &&Chain multiple commands with
prefix = 'cd ~/application/ && {}'
for _cmd in cmd:
command = prefix.format(_cmd)
p = cmdline(command)
print 'command:' + command
#Chat to notify when standard error is present
errors = p.stderr.readlines()
if errors:
error_message = ''.join(errors)
chat(error_message)
Execution result
command:cd ~/application/ && python manage.py test_json
ERROR:Traceback (most recent call last):
File "manage.py", line 10, in <module>
...
IOError: [Errno 2] No such file or directory: u'..../test.json'
command:cd ~/application/ && python manage.py test_battle
I'm sure there are people who know more convenient ways (・ ㅂ ・) و
Recommended Posts