caesar
caesar

Reputation: 3135

Getting terminal output of a command from python

I've tried to write a function that includes bash command. I want to assign the output of the command to variable in my python I mean, the function gitCheck find the directory of my git Repository and assign it to gitRep but It gives me only 0. Is there anyone to know how could I do that ? Thanks in advance

def gitCheck():
reference_repositories_path="cat $HOME/.git_reference_repositories | sed 's/GIT_REFERENCES_PATH=//'"
gitRep=os.system(reference_repositories_path)
print gitRep

output should be /home/gwapps/Desktop/GIT_REFERENCE_REPOSITORIES but it gives me 0

Upvotes: 1

Views: 593

Answers (1)

alecxe
alecxe

Reputation: 474141

You are getting the exit status. According to os.system() docs:

On Unix, the return value is the exit status of the process encoded in the format specified for wait().

...

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.

So, if you want to retrieve the output of the command, use subprocess module. There are tons of examples here on SO, e.g.:

Upvotes: 1

Related Questions