Skip to content

Instantly share code, notes, and snippets.

@tadone
Last active October 13, 2017 14:48
Show Gist options
  • Save tadone/0b241b1e67816c7fbf0b8977614d5913 to your computer and use it in GitHub Desktop.
Save tadone/0b241b1e67816c7fbf0b8977614d5913 to your computer and use it in GitHub Desktop.
Subprocess
# Import whole module
import subprocess
# Import selected calls from module
from subprocess import Popen, PIPE
process = Popen(['cat', 'test.py'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print(stdout)
# Run the command described by args.
# Wait for command to complete, then return the returncode attribute.
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
#Example:
import subprocess
subprocess.call(["ls", "-l"]) # Same as ls -l in shell
# Run command with arguments and return its output as a byte string.
# Save process output (stdout)
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
#Example:
output_string = subprocess.check_output(["echo", "Hello World!"])
print("Output String = " + output_string)
### Save subprocess output to file
with open('file.txt', 'w') as my_file:
subprocess.call(['ls', '-l'], stdout=my_file, stderr=my_file)
### MySQL Dump as subprocess
with open("mysqldump.sql",'wb') as out:
subprocess.check_call(["mysqldump", "-u", "usernmae", "-ppassword", "-h", "dbserver_name", database_name], stdout=out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment