[Tutor] Python Fails to Change Directory

Dave Angel d at davea.name
Sun Apr 15 13:34:21 CEST 2012


On 04/15/2012 01:32 AM, Steven D'Aprano wrote:
> 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 interpreted Andrew's description somewhat differently.  He's executing
a Python program before executing some other commands.  So those other
commands are shell commands, not Python lines.  In that case, Python has
nothing to do with the problem.

Andrew, are you trying to do this sort of thing ?

davea at think:~/tmp$ python program.py
davea at think:~/tmp$ myother
davea at think:~/tmp$ programs
davea at think:~/tmp$

where 'myother' and 'programs' are other "commands" or (programs and
shell scripts)?

In that case, nothing that your python program can normally do can alter
either the cwd or the environment.  The shell explicitly creates a new
environment for the python program, and tosses it away when it exits.

You can demonstrate it for yourself, easily enough.  The following   in
my (bash) environment.  With an executable file called change.sh, as
follows:

davea at think:~/tmp$ cat change.sh
#!/bin/bash
cd other
pwd
davea at think:~/tmp$ ./change.sh
/home/davea/tmp/other
davea at think:~/tmp$ pwd
/home/davea/tmp

( Notice the pwd of the shell did NOT change. )

davea at think:~/tmp$ source ./change.sh
/home/davea/tmp/other
davea at think:~/tmp/other$ pwd
/home/davea/tmp/other
davea at think:~/tmp/other$

Unfortunately, I don't know of any workaround for this.  The obvious
extension would be:

davea at think:~/tmp$ source python myprogram.py
bash: source: /usr/bin/python: cannot execute binary file

When I've had this type of problem I've resorted to creating a text file
from the Python script, and doing a chmod +x on that file and source'ing
it from bash.

-- 

DaveA



More information about the Tutor mailing list