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,873
  • 18
  • 56
  • 99

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
  • 63,701
  • 20
  • 147
  • 175
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
  • 842,883
  • 184
  • 1,785
  • 1,677
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
  • 128,818
  • 30
  • 231
  • 230
1

Current directory full path:

import os
print os.getcwd()
Johnny
  • 512
  • 2
  • 7
  • 18