How do I change the current directory from a python script?

I am trying to implement my own version of the "cd" command, which presents the user with a list of hard-coded directories to choose from, and the user must enter the number corresponding to the entry in the list. Now the program, named my_cd.py, should effectively "cd" the user into the selected directory. An example of how this should work:

/some/directory
$ my_cd.py
1) ~
2) /bin/
3) /usr
Enter menu selection, or q to quit: 2

/bin
$

I am currently trying to use "cd" os.chdir('dir'). However, this does not work, perhaps because it my_cd.pystarts in its own child process. I tried wrapping the call my_cd.pyin a bash script source with the name my_cd.sh:

#! /bin/bash
function my_cd() {
    /path/to/my_cd.py
}

/some/directory
$ . my_cd.sh
$ my_cd
... shows list of dirs, but doesn't 'cd' in the interactive shell

, ? python script?

+3
5

. . Python script , , script .

+1

bash :

#! /bin/bash
function my_cd() {
    cd `/path/to/my_cd.py`
}

Python, cosmetic ( , ..) sys.stderr, os.chdir print ( sys.stdout) .

+6

my_cd.py:

#!/usr/bin/env python
import sys

dirs = ['/usr/bin', '/bin', '~']
for n, dir in enumerate(dirs):
    sys.stderr.write('%d) %s\n' % (n+1, dir))
sys.stderr.write('Choice: ')
n = int(raw_input())
print dirs[n-1]

:

nosklo:/tmp$ alias mcd="cd \$(/path/to/my_cd.py)"
nosklo:/tmp$ mcd
1) /usr/bin
2) /bin
3) ~
Choice: 1
nosklo:/usr/bin$ 
+3

, "bash", bash:

$ cat select_cd
#!/bin/bash

PS3="Number: "

dir_choices="/home/klittle /local_home/oracle"

select CHOICE in $dir_choices; do
   break
done

[[ "$CHOICE" != "" ]] &&  eval 'cd '$CHOICE

script source'd, :

$ pwd
/home/klittle/bin
$ source select_cd
1) /home/klittle
2) /local_home/oracle
Number: 2
$ pwd
/local_home/oracle

,

$ alias mycd='source /home/klittle/bin/select_cd'
$ mycd
1) /home/klittle
2) /local_home/oracle
Number:

, , , - , bash script, dir, python cd.

+2

, , .

bash my_cd :

function my_cd() {
    exec /path/to/my_cd.py "$BASH" "$0"
}

python script :

os.execl(sys.argv[1], sys.argv[2])

import os, sys script.

But note that this is a border hack. Your shell dies, replacing itself with a python script, working in the same process. The Python script makes changes to the environment and replaces the shell, back, still in the same process. This means that if there are other local unsaved and unexposed data or environment in the previous shell session, they will not be saved in the new one. This also means that the rc and profile scripts will run again (usually this is not a problem).

+1
source

Source: https://habr.com/ru/post/1739696/


All Articles