簡體   English   中英

從腳本目錄/當前目錄運行 Python 腳本

[英]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

如果您只想更改 python 腳本:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM