Last active
February 20, 2017 05:28
-
-
Save ruxi/7ac6f6c3e44c4855761f2bcafda95159 to your computer and use it in GitHub Desktop.
invoke bash commands in python3.6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function | |
__author__ = 'github.com/ruxi' | |
__license__= 'MIT' | |
import sys | |
import os.path | |
import subprocess | |
def runbash(cmd, cwd=".", shell=True, logname="runbash.log", ioprint=True): | |
""" | |
cmd: bash command to run. example: 'ls -l' | |
cwd: working directory of child process | |
logname: (optional) | |
- logname is name of log file | |
- False to turn off logging | |
ioprint: (optional) | |
- print output to py terminal | |
""" | |
# make cwd if not exist | |
if sys.version_info > (3,0,0): | |
os.makedirs(cwd, exist_ok=True) | |
# invoke bash process | |
process = subprocess.Popen(cmd, shell=shell | |
, stdout=subprocess.PIPE | |
, stderr=subprocess.STDOUT | |
, bufsize=1 | |
, cwd=cwd) | |
# standard output | |
if logname: | |
filename = os.path.join(cwd, logname) | |
logfile = open(filename, 'w') | |
for line in iter(process.stdout): | |
msg = line.decode() | |
if ioprint: | |
print(msg, end='') | |
if logname: | |
logfile.write(msg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
might be compatible with 2.7