简体   繁体   English

使用 python 在命令提示符中更改当前工作目录

[英]Change current working directory in command prompt using python

I am trying to write a python script that will change my cwd to the desired directory.我正在尝试编写一个 python 脚本,它将我的cwd更改为所需的目录。 I was not able to do this task directly from python so I wrote a simple batch script to do that.我无法直接从 python 执行此任务,因此我编写了一个简单的batch脚本来执行此操作。

Changedir.bat

@echo off
chdir /D F:\cygwin\home\

If I execute the above script directly in my cmd it works fine but if I try to execute it with a python script nothing happens.如果我直接在我的cmd执行上面的脚本它工作正常但是如果我尝试用 python 脚本执行它什么也没有发生。 My cwd remains same.我的cwd保持不变。

PythonScript.py

import shlex,subprocess

change_dir = r'cmd.exe /c C:\\Users\\test.bat'
command_change = shlex.split(change_dir)
subprocess.call(command_change)

Of course this can't work, because subprocess.call is spawning whole new process for your script.当然这行不通,因为 subprocess.call 正在为您的脚本生成全新的进程。 This executes the script in a completely separate environment.这将在完全独立的环境中执行脚本。

If you want to change directory in the command prompt you have to use either cd or a .bat script.如果您想在命令提示符中更改目录,您必须使用cd.bat脚本。

You can't get another process (ie Python) to do it because changes to the current directory, made in another process are not reflected back to the parent process.您不能让另一个进程(即 Python)来执行此操作,因为在另一个进程中对当前目录所做的更改不会反映回父进程。 The reason the .bat script works is that it is processed by the command shell that invokes it rather than by a child process. .bat脚本工作的原因是它由调用它的命令外壳程序处理,而不是由子进程处理。

You could try this.你可以试试这个。 It works in Linux to change the CWD of the current shell.它适用于 Linux 以更改当前 shell 的 CWD。 It is horrible.这太可怕了。

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_shell_working_directory(dest):
    put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM