我正在嘗試編寫一個腳本,該腳本從配置文件中提取一些路徑并調用系統 shell 以使用該路徑作為命令的一部分來運行命令。它基本上是一個解壓縮目錄中所有文件的摘要腳本。請記住,我正在自學 Python,這是我的第一個 Python 腳本,也是我的第一篇文章。請原諒我在禮儀方面的任何錯誤。目標是讓命令“C:\Program Files\WinRAR\Rar.exe x”在目錄上運行。不幸的是,我了解到 Python 不允許您將字符串連接到 Path 對象,大概是因為它們是兩種不同的元素類型。我有以下內容:在配置文件中:[Paths]WinrarInstallPath = C:\Program Files\WinRAR\NewFilesDirectory = M:\Directory\Where\Rar Files\Are\Located腳本:**SOME CODE***new_files_dir = Path(config.get('Paths', 'NewFilesDirectory'))winrar_dir = Path(config.get('Paths', 'WinrarInstallPath'))**SOME MORE CODE**os.chdir(new_files_dir)for currentdir, dirnames, filenames in os.walk('.'): os.system(winrar_dir + "rar.exe x " + os.getcwd() + currentdir[1:] + '\\*.rar')這給了我錯誤“TypeError:+的不支持的操作數類型:'WindowsPath'和'str'”我試過了os.system(str(winrar_dir) + "rar.exe x " + os.getcwd() + currentdir[1:] + '\\*.rar')但它不處理目錄名稱中的空格。我也試過os.system(os.path.join(winrar_dir, "rar.exe x ") + os.getcwd() + currentdir[1:] + '\\*.rar')結果相同我意識到我可以從一開始就將它視為一個字符串并執行以下操作wrd = config.get('Paths', 'WinrarInstallationPath')winrar_dir = '"' + wrd + '"'os.system(winrar_dir + "rar.exe x " + os.getcwd() + currentdir[1:] + '\\*.rar')但是到目前為止,Python 一直很流暢,而且感覺很笨拙,所以我覺得我錯過了一些東西,但到目前為止我還沒有找到答案。
2 回答

蕭十郎
TA貢獻1815條經驗 獲得超13個贊
不要使用os.system
. 使用subprocess.call
:
os.system(winrar_dir + "rar.exe x " + os.getcwd() + currentdir[1:] + '\\*.rar')
該列表實際上就是 argv 數組。無需為外殼報價。
subprocess.call([os.path.join(winrar_dir, 'rar.exe'), 'x', os.getcwd(), os.path.join(currentdir[1:], '*.rar')])
您可能還會看到我不喜歡 pathlib 模塊。我使用了它的前身路徑,只發現它的 walkfiles 方法有用。

Cats萌萌
TA貢獻1805條經驗 獲得超9個贊
如果您要嘗試添加到一個pathlib.Path對象,您需要添加它的joinpath方法以添加到路徑中,而不是+像您將用于字符串一樣的運算符(這就是給您的TypeError)。
# From the docs:
Path('c:').joinpath('/Program Files')
Out[]: PureWindowsPath('c:/Program Files')
如果您仍然遇到問題,請使用Path.exists()方法或Path.glob方法測試您正在讀取的路徑是否指向正確的位置。
添加回答
舉報
0/150
提交
取消