How do I change the working directory in Python?

前端 未结 14 1438
天涯浪人
天涯浪人 2020-11-22 01:59

cd is the shell command to change the working directory.

How do I change the current working directory in Python?

14条回答
  •  Happy的楠姐
    2020-11-22 02:08

    As already pointed out by others, all the solutions above only change the working directory of the current process. This is lost when you exit back to the Unix shell. If desperate you can change the parent shell directory on Unix with this horrible hack:

    def quote_against_shell_expansion(s):
        import pipes
        return pipes.quote(s)
    
    def put_text_back_into_terminal_input_buffer(text):
        # use of this means that it only works in an interactive session
        # (and if the user types while it runs they could insert characters between the characters in 'text'!)
        import fcntl, termios
        for c in text:
            fcntl.ioctl(1, termios.TIOCSTI, c)
    
    def change_parent_process_directory(dest):
        # the horror
        put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"\n")
    

提交回复
热议问题