Change Working Directory in Shell with a Python Script

Change working directory in shell with a python script

Others have pointed out that you can't change the working directory of a parent from a child.

But there is a way you can achieve your goal -- if you cd from a shell function, it can change the working dir. Add this to your ~/.bashrc:

go() {
cd "$(python /path/to/cd.py "$1")"
}

Your script should print the path to the directory that you want to change to. For example, this could be your cd.py:

#!/usr/bin/python
import sys, os.path
if sys.argv[1] == 'tdi': print(os.path.expanduser('~/long/tedious/path/to/tdi'))
elif sys.argv[1] == 'xyz': print(os.path.expanduser('~/long/tedious/path/to/xyz'))

Then you can do:


tdi@bayes:/home/$> go tdi
tdi@bayes:/home/tdi$> go tdi

Change working directory from python or shell script

Since python runs in its own process, it won't be able to change the current directory of your shell. However, you could do something like this:

change_path() {
# prog.py figures out the real path that you want and prints
# it to standard output
local new_path=$(python prog.py some_path1) # could use an argument "$1"
cd "$new_path"
}

How to change the directory of Linux in python script?

It's much better to use the subprocess module. It has a nicer API and does accept a keyword for this:

>>> import subprocess as sp
>>> sp.call("ls -ll", cwd='/tmp', shell=True)

How to change working directory of Python script during execution?

There is return statement before os.chdir, so that line is not executed.

Equivalent of shell 'cd' command to change the working directory?

You can change the working directory with:

import os

os.chdir(path)

There are two best practices to follow when using this method:

  1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
  2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

How to know/change current directory in Python shell?

You can use the os module.

>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'

But if it's about finding other modules: You can set an environment variable called PYTHONPATH, under Linux would be like

export PYTHONPATH=/path/to/my/library:$PYTHONPATH

Then, the interpreter searches also at this place for imported modules. I guess the name would be the same under Windows, but don't know how to change.

edit

Under Windows:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(taken from http://docs.python.org/using/windows.html)

edit 2

... and even better: use virtualenv and virtualenv_wrapper, this will allow you to create a development environment where you can add module paths as you like (add2virtualenv) without polluting your installation or "normal" working environment.

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

Changing directory from a python script: how to not open a new shell

The problem is that python runs in a child process, and it "can't" alter the current directory of the parent (I say "can't", but there are probably some debuggers that could do it - don't go there!).

The simplest solution is to use a function instead. For example:

bk() {
dir="/home/user/somewhere"

# equivalent to "if os.path.isdir(dir): os.chdir(dir)"
[[ -d $dir ]] && cd "$dir"
}

Put this into a file called bk.sh (for example).

To compile and load the function do:

. bk.sh

Then use bk whenever you want to change directory.

The difference with a function is that it runs in the current process, it does not create a new shell.

Change the current directory pwd, from the python script itself

The only way I can think of is actual workaround. Where you pick up the output of your
script in current shell. Otherwise eveything gets executed in subshell.

myprogram.py

import os
new_dir = "/home/cabox/workspace"
os.chdir(new_dir)
print os.getcwd()

In linux shell:

cabox@box-codeanywhere:~/workspace/cliRtStocks$ pwd
/home/cabox/workspace/cliRtStocks

cabox@box-codeanywhere:~/workspace/cliRtStocks$ a=`python myprogram.py`;cd $a

cabox@box-codeanywhere:~/workspace$ pwd
/home/cabox/workspace
cabox@box-codeanywhere:~/workspace$

Change directory from python script for calling shell

You can't do that directly from python, as a child process can never change the environment of its parent process.

But you can create a shell script that you source from your shell, i.e. it runs in the same process, and in that script, you'll call python and use its output as the name of the directory to cd to:

/home/choroba $ cat 1.sh
cd "$(python -c 'print ".."')"
/home/choroba $ . 1.sh
/home $


Related Topics



Leave a reply



Submit