Thanks for your answer. I know why the why os.system or os.chdir failed change my directory.

But Sorry for my un-clear description of my problem. Currently I work in window platform, use cmd.exe instead of bash.

I mentioned bash just as a example to illustrate my problem.

    Thanks and Regards

Samuel Yin

Mike Meyer 写道:
Samuel Yin <[EMAIL PROTECTED]> writes:
  
Hi, guys,

This should be a simple problem, but I just can not resolve it. I just
want to use a python script to change my working directory. see my
following code:

# mycd.py
1) destdir = "xxxxxxxx"
2) command = "cd "+ destdir
3) os.system(command)
4) os.chdir(destdir)

But neither 3) nor 4) is used, I just can not change the directory after
execute mycd.py. This remind me of bash script. If you change directory
in your bash script file, it will only impact the sub process of that
script, except that you invoke that bash script by ./script_file_name.
But what should I do in the case of python script?
    

Actually, one solution is a level of indirection worse than the bash
script. Doing a cd changes the current directory of the process that
executes the cd system call. In a bash script, it's the shell
executing the script. In your python script, os.system launches
another process to run the command, and it's *that* process that has
it's directory changed. The os.chdir changes the shell of the python
interpreter, which still doesn't do you any good.

One solution is to switch to a shell that understands Python, and have
that execfile your script. There is a Python environment that can be
configured to be used as a shell, but I can't remeber it's name.

If you want to stay with bash, your solutions are the same as they are
for setting an environment variable in the parent shell.  You can
google for that for a long discussion of the issues.

The solution I liked from that thread was an alias:

In your bash do: alias mycd="eval $(python mycd.py)"

mycd.py looks like:
destdir = 'xxxxxx'
command = 'os ' + destdir
print command

At the bash prompt you enter the command "mycd", your python script
builds a command for the shell to execute and prints it, the eval
reads that output and executes it in your shell.

If you want to pass arguments to the python script, you'll need to use
a shell function instead of an alias.

     <mike
  

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to