我正在尝试在 foldersystem 中使用 os.walk() 找到几个 'my_file.bat',如果文件名匹配它应该用 subprocess.call() 或 .run() 调用。问题是 os.path.abspath('my_file.bat') 返回一个联合 'where\i\ran\the\script\from' + ˇmy_file.batˇ.
谁能告诉我为什么会这样,我怎样才能得到 'my_file.bat' 位置?
import os
import subprocess
for root, dir, name in os.walk(r'C:\the\path\i\am\using\for\the\folder\system'):
for filename in name:
if filename == 'my_file.bat':
my_file_path = os.path.abspath('my_file.bat')
os.chdir(my_file_path)
subprocess.call('my_file.bat')
请您参考如下方法:
abspath 不会帮助您,因为它是从当前目录 计算路径。 abspath 如何知道 walk 正在做什么?
除了 os.chdir(my_file_path) 尝试使用 file 作为参数更改目录...好吧,最好不要使用 chdir在 python 脚本中,曾经。
how could I get the 'my_file.bat' location?
你不需要它(它不足以执行文件)。你想要的是执行文件,当前目录设置为脚本的目录(使.bat文件更简单)
另一方面,root 变量提供文件所在的目录。所以我会像这样重写你的代码:
for root, dir, name in os.walk(r'C:\the\path\i\am\using\for\the\folder\system'):
for filename in name:
if filename.lower() == 'my_file.bat':
subprocess.call('my_file.bat',shell=True,cwd=root)
添加 cwd=root 允许 call 在执行之前(并且仅在调用中)将目录更改为脚本目录,其中 shell=True(您的下一个问题)确保您可以从 subprocess.call
如果文件名为 MY_FILE.BAT,也使用小写比较。由于所有这些怪癖,您必须爱上 Windows。
