[英]Run Python Script From Script Directory/Current Directory
[介紹]
你好! 我正在編寫一個 python 腳本來自動安裝 UWP-Apps,我已經很久沒有接觸 Python 了; 直到今天。 該腳本使用腳本目錄中的依賴項,我查看了我的舊腳本並找到了這個特定的代碼。
os.chdir(os.path.dirname(sys.argv[0]))
[問題]
但是,使用上面的代碼不適用於我當前的腳本,但在舊腳本上運行良好。 在上面使用時,它顯示:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''
已經在互聯網上查找有關此主題的信息; 但他們中的大多數人都在談論從外部/不同目錄運行腳本,這導致我陷入死胡同。
任何幫助表示贊賞:)
.py
文件:cd path/to/python/file && python ../.py
在運行 puthon 腳本的目錄中將其另存為runPython.sh
:
#!/bin/sh
cd path/to/python/file
python ../script.py
使其可執行:
chmod +x ./runPython.sh
然后你可以簡單地進入你的目錄並運行它:
./runPython.sh
mydir = os.getcwd() # would be the folder where you're running the file
mydir_tmp = "path/to/python/file" # get the path
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd()
您收到錯誤的原因是因為sys.argv[0]
是文件本身的名稱,您可以將目錄作為字符串傳遞並使用sys.argv[1]
代替。
import os
from os.path import abspath, dirname
os.chdir(dirname(abspath(__file__)))
可以使用dirname(abspath(__file__)))
獲取python腳本的父目錄,將os.chdir
放入其中,使腳本在其所在目錄運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.