Change working directory in shell with a python script

前端 未结 5 1298
遇见更好的自我
遇见更好的自我 2020-12-06 01:16

I want to implement a userland command that will take one of its arguments (path) and change the directory to that dir. After the program completion I would like the shell t

相关标签:
5条回答
  • 2020-12-06 01:34

    That is not going to be possible.

    Your script runs in a sub-shell spawned by the parent shell where the command was issued.

    Any cding done in the sub-shell does not affect the parent shell.

    0 讨论(0)
  • 2020-12-06 01:35

    I shall try to show how to set a Bash terminal's working directory to whatever path a Python program wants in a fairly easy way.

    Only Bash can set its working directory, so routines are needed for Python and Bash. The Python program has a routine defined as:

    fob=open(somefile,"w")
    fob.write(dd)
    fob.close()
    

    "Somefile" could for convenience be a RAM disk file. Bash "mount" would show tmpfs mounted somewhere like "/run/user/1000", so somefile might be "/run/user/1000/pythonwkdir". "dd" is the full directory path name desired.

    The Bash file would look like:

    #!/bin/bash
    #pysync ---Command ". pysync" will set bash dir to what Python recorded
    cd `cat /run/user/1000/pythonwkdr`
    
    0 讨论(0)
  • 2020-12-06 01:46

    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
    
    0 讨论(0)
  • 2020-12-06 01:50

    cd is exclusively(?) implemented as a shell internal command, because any external program cannot change parent shell's CWD.

    0 讨论(0)
  • 2020-12-06 01:58

    As codaddict writes, what happens in your sub-shell does not affect the parent shell. However, if your goal is present the user with a shell in a different directory, you could always have Python use os.chdir to change the sub-shell's working directory and then launch a new shell from Python. This will not change the working directory of the original shell, but will leave the user with one in a different directory.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题