[Tutor] Python Fails to Change Directory

Steven D'Aprano steve at pearwood.info
Sun Apr 15 07:32:29 CEST 2012


Andrew Jahn wrote:
> Hi all,
> 
> I am attempting to use a Python program to change into a specified
> directory before executing some commands. However, when I call the Python
> program from my Unix shell (tcsh) using a command such as
> 
> "python myprogram.py"
> 
> It runs without changing directory. Just to clarify, the lines of code in
> question are the following:
> 
> import os
> MyDir = "/usr/local/myDir"
> os.system("cd "+myDir)

That's not the code you are running, because it gives a NameError. Please copy 
and paste any code snippets you give, don't retype them (especially not from 
memory!) since you will likely introduce errors. The above error is trivial to 
fix, but who knows what other errors you have introduced?

In any case, os.system can't help you, because that starts a new external 
process, it doesn't change the directory of the current process (your Python 
script).


> I have also tried "os.chdir(MyDir)", but that doesn't work either - it just
> runs without actually changing directory.

I find that very hard to believe. Can you explain why you think it doesn't 
change directory? Try this:


import os
print os.getcwd()
os.chdir("/usr/local/myDir")
print os.getcwd()

What does it print?




-- 
Steven



More information about the Tutor mailing list