Skip to content

Instantly share code, notes, and snippets.

@ruxi
Last active February 20, 2017 05:28
Show Gist options
  • Save ruxi/7ac6f6c3e44c4855761f2bcafda95159 to your computer and use it in GitHub Desktop.
Save ruxi/7ac6f6c3e44c4855761f2bcafda95159 to your computer and use it in GitHub Desktop.
invoke bash commands in python3.6
#!/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)
@ruxi
Copy link
Author

ruxi commented Feb 20, 2017

might be compatible with 2.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment