My coworker is having trouble with a Python install. When running the code below, from 'C:\my\folder\'
, 'C:\'
is returned instead of the current working directory. When I or anyone else run the script on our systems, we get 'C:\my\folder\'
.
We're assuming that some global setting must be causing the issue, so I've had the person uninstall Python, delete the local Python2.7 folder, clean the registry and reinstall the Python, but it's still not working.
NOTE: We have a large number of legacy scripts, so revising all of them to use subprocess is impractical. :(
Any ideas?
Environment: Windows XP, Python 2.7
import os
#
# This test script demonstrates issue on the users computer when python invokes
# a subshell via the standard os.system() call.
#
print "This is what python thinks the current working directory is..."
print os.getcwd()
print
print
print "but when i execute a command *from* python, this is what i get for the current working directory"
os.system('echo %cd%')
raw_input()
To change the current working directory(CWD) os. chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.
path. isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows symbolic link, that means if the specified path is a symbolic link pointing to a directory then the method will return True.
chdir(path) before invoking the command.
An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs.
you could also try something like this
os.chdir("C:\\to\\my\\folder")
print os.system("echo %CD%")
raw_input()
also to get the current working directory i use a different approach
cur_dir = os.path.abspath(".")
os.getcwd()
isn't guarenteed to get the location of your script when it is called. Your coworker might be calling the script a different way or his computer (for some reason) handles the current working directory differently.
To get the actual script location you should use the following:
import os
os.path.dirname(os.path.realpath(__file__))
As an example I wrote getcwd
and the above line in the same script and ran it from C:\
.
Results:
C:\>python C:\Users\pies\Desktop\test.py
C:\Users\pies\Desktop
C:\
It depends on what your real purpose for this script is, whether you actually need the current working directory, or just the current scripts directory. As a little caveat this call will return a different directory if you call a script from script which then uses this call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With