Skip to content

Instantly share code, notes, and snippets.

@i5on9i
Last active June 2, 2016 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save i5on9i/21884c7d77b7cfb42749157db3e6d8f6 to your computer and use it in GitHub Desktop.
Save i5on9i/21884c7d77b7cfb42749157db3e6d8f6 to your computer and use it in GitHub Desktop.
from subprocess import Popen, PIPE
# This is the exact same as running: ls -al | sort
p1 = Popen(["ls", "-al"], stdout=PIPE)
p2 = Popen(["sort"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
####################################
from subprocess import Popen, PIPE
cmd = 'blah'
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
####################################
import sys
sys.stdout = open('file', 'w')
print 'test'
####################################
# On Windows with shell=True, the COMSPEC environment variable specifies the default shell.
# The only time you need to specify shell=True on Windows is
# when the command you wish to execute is built into the shell (e.g. dir or copy).
# You do not need shell=True to run a batch file or console-based executable.
# the below command is same as the command,
# dir wrong_file_name 2> err_file.log
from subprocess import call
cmd = 'dir wrong_file_name'
call(cmd, shell=True, stderr=open('err_file.log', 'w'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment