[英]Change current working directory in command prompt using python
我正在嘗試編寫一個 python 腳本,它將我的cwd
更改為所需的目錄。 我無法直接從 python 執行此任務,因此我編寫了一個簡單的batch
腳本來執行此操作。
Changedir.bat
@echo off
chdir /D F:\cygwin\home\
如果我直接在我的cmd
執行上面的腳本它工作正常但是如果我嘗試用 python 腳本執行它什么也沒有發生。 我的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)
當然這行不通,因為 subprocess.call 正在為您的腳本生成全新的進程。 這將在完全獨立的環境中執行腳本。
如果您想在命令提示符中更改目錄,您必須使用cd
或.bat
腳本。
您不能讓另一個進程(即 Python)來執行此操作,因為在另一個進程中對當前目錄所做的更改不會反映回父進程。 .bat
腳本工作的原因是它由調用它的命令外殼程序處理,而不是由子進程處理。
你可以試試這個。 它適用於 Linux 以更改當前 shell 的 CWD。 這太可怕了。
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.