简体   繁体   English

使用Python脚本执行批处理文件

[英]Execute batch file using Python script

I'm trying to execute a batch file using a Python script. 我正在尝试使用Python脚本执行批处理文件。 Is this possible? 这可能吗? The Python script is in a different folder than the batch file. Python脚本与批处理文件位于不同的文件夹中。 For example, the Python script is in C:\\users\\me\\desktop\\python while the batch file is in a folder C:\\users\\me\\desktop\\batch . 例如,Python脚本位于C:\\users\\me\\desktop\\python而批处理文件位于文件夹C:\\users\\me\\desktop\\batch I prefer not to use the full path to the batch file because I want it to work on other people's computer as well (ie the C:\\users\\me part might be different). 我不想使用批处理文件的完整路径,因为我希望它也可以在其他人的计算机上工作(即C:\\users\\me部分可能有所不同)。

This is the script I tried (executed from the "python" folder on desktop) 这是我尝试的脚本(从桌面上的“ python”文件夹执行)

from subprocess import call

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

Result: file not found 结果:找不到文件

Backslash escapes special characters in python. 反斜杠在python中转义特殊字符。 Therefore, the paths that you are creating here are not the ones you think they are: 因此,您在此处创建的路径不是您认为的路径:

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

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

Use raw strings instead: 使用原始字符串:

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

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

And actually, the best way to combine path segments in python is by using os.path.join . 实际上,在python中组合路径段的最佳方法是使用os.path.join This will automatically take care of the backslash vs. slash issues for Unix-lie vs. Windows operating systems. 这将自动解决Unix-lie与Windows操作系统之间的反斜杠与斜杠问题。

Use os.path , 使用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