Search code examples
pythonpython-2.7windows-7python-os

string variable of cwd


Input

import os
my_cwd = str(os.system("cd"))

Output

C:\ProgramData\Anaconda2

Input

my_cwd

Output

'0'

I would expect calling my_cwd would return 'C:\ProgramData\Anaconda2' what am I missing?


Solution

  • os.system returns the return code of the command as an integer (that's why you tried to convert to str), not the output of the command as a string.

    To get the output, you could use subprocess.check_output (subprocess.run in python 3.5+) with shell=True since cd is built-in:

    import subprocess
    value = subprocess.check_output(["cd"],shell=True)
    

    (check_output raises an exception if the command fails, though)

    You also have to "cleanup" the output by using value.rstrip() and decode the result into a string, since subprocess.check_output returns a bytes object... Also, your code is not portable on Linux, since the required command would be pwd.

    Well, that very complex to just get the current directory (leave that kind of stuff for cls or clear commands). The most pythonic way to get it is to use:

    os.getcwd()