Skip to content

Instantly share code, notes, and snippets.

@sparkydogX
Created December 7, 2018 07:38
Show Gist options
  • Save sparkydogX/e88b95586c843398f057bc28ce602277 to your computer and use it in GitHub Desktop.
Save sparkydogX/e88b95586c843398f057bc28ce602277 to your computer and use it in GitHub Desktop.
Execute terminal command and get output in python.
# For short output.
import subprocess
cmd = "git branch | grep '*' | cut -d ' ' -f2"
output = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True).communicate()[0]
print(output.strip()) # For single line output.
# For long output.
import subprocess
import tempfile
cmd = "git branch | grep '*' | cut -d ' ' -f2"
with tempfile.TemporaryFile() as tempf:
proc = subprocess.Popen(cmd, stdout=tempf,shell=True)
proc.wait()
tempf.seek(0)
print(tempf.read())
@nachakr
Copy link

nachakr commented Jan 5, 2022

I have a shell script which I am executing from git bash here.
I automated the same using python subprocess which will launch gitbash and execute the shell script.
I am not able to get the gitbash console output to python console.
I tried above approach it did not work, all I get for print(temp.read()) is b' '

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