簡體   English   中英

使用Python腳本執行批處理文件

[英]Execute batch file using Python script

我正在嘗試使用Python腳本執行批處理文件。 這可能嗎? Python腳本與批處理文件位於不同的文件夾中。 例如,Python腳本位於C:\\users\\me\\desktop\\python而批處理文件位於文件夾C:\\users\\me\\desktop\\batch 我不想使用批處理文件的完整路徑,因為我希望它也可以在其他人的計算機上工作(即C:\\users\\me部分可能有所不同)。

這是我嘗試的腳本(從桌面上的“ python”文件夾執行)

from subprocess import call

path = "..\batch"
call([path+"\test.bat"])

結果:找不到文件

反斜杠在python中轉義特殊字符。 因此,您在此處創建的路徑不是您認為的路徑:

In [1]: test = "..\bfoo"

In [2]: test
Out[2]: '..\x08foo'

使用原始字符串:

In [3]: test = r"..\bfoo"

In [4]: test
Out[4]: '..\\bfoo'

實際上,在python中組合路徑段的最佳方法是使用os.path.join 這將自動解決Unix-lie與Windows操作系統之間的反斜杠與斜杠問題。

使用os.path

import os 

dir_path = os.path.dirname(os.path.realpath(__file__))  # get the full path of the Python file
parent_dir = os.path.dirname(dir_path)

new_path = os.path.join(parent_dir, 'bath', 'test.bat')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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