4

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?

Itai Ganot
  • 5,089
  • 13
  • 51
  • 91

4 Answers4

17

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.

Lev Levitsky
  • 59,844
  • 20
  • 139
  • 166
2

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)
unutbu
  • 777,569
  • 165
  • 1,697
  • 1,613
1

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'
jamylak
  • 120,885
  • 29
  • 225
  • 225
1

Current directory full path:

import os
print os.getcwd()
Johnny
  • 470
  • 1
  • 7
  • 18