I'm trying to get the output of pwd
:
#!python
import os
pwd = os.system("pwd")
print (pwd)
it prints 0 which is the successful exit status instead the path. How can i get the path instead?
I'm trying to get the output of pwd
:
#!python
import os
pwd = os.system("pwd")
print (pwd)
it prints 0 which is the successful exit status instead the path. How can i get the path instead?
Running system commands is better done with subprocess
, but if you are using os
already, why not just do
pwd = os.getcwd()
os.getcwd()
is available on Windows and Unix.
To get the current working directory, use os.getcwd(). But in general, if you want both the output and the return code:
import subprocess
PIPE = subprocess.PIPE
proc = subprocess.Popen(['pwd'], stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
errcode = proc.returncode
print(out)
print(errcode)
You can't do that with os.system
, although os.popen
does return that value for you:
>>> import os
>>> os.popen('pwd').read()
'/c/Python27\n'
However the subprocess
module is much more powerful and should be used instead:
>>> import subprocess
>>> p = subprocess.Popen('pwd', stdout=subprocess.PIPE)
>>> p.communicate()[0]
'/c/Python27\n'