Reputation: 29
I'm trying to find several 'my_file.bat'
with os.walk()
, in a foldersystem
, if the filename matches it should be called with subprocess.call()
or .run()
. The problem is that the os.path.abspath('my_file.bat')
gives back a joint 'where\i\ran\the\script\from' + ˇmy_file.batˇ
.
Could anyone tell me why is this happening and how could I get the 'my_file.bat'
location?
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')
Upvotes: 1
Views: 101
Reputation: 29
so my solution took some time, but this worked for me:
batchFileFullPath = os.path.join(batchFileLocation, 'my_bat_file.bat')
p = subprocess.Popen(os.path.abspath(batchFileFullPath), stdin=subprocess.PIPE, cwd=batchFileLocation)stdout, stderr = p.communicate()
To be honest I have no idea why it works, but it does. Thanks for your ideas. :)
Upvotes: 0
Reputation: 42748
Better use pathlib
, which makes the for-loop much easier:
from pathlib import Path
import subprocess
root = Path(r'C:\the\path\i\am\using\for\the\folder\system')
for filename in root.rglob('my_file.bat')
subprocess.call(filename.name, cwd=filename.parent)
Upvotes: 2
Reputation: 39
You should be able to get the path to your file by using:
my_file_path = root+"\\"+filename
The reason you are getting the wrong location is because python returns the current folder location with name when using os.path.abspath()
Upvotes: 0
Reputation: 22766
To get the path of the file that you got through os.walk
, use os.path.join
to join the root
and the filename
:
my_file_path = os.path.join(root, 'my_file.bat')
Upvotes: 1
Reputation: 140168
abspath
isn't going to help you since it computes the path from current directory. How can abspath
be aware of what walk
is doing ?
Besides os.chdir(my_file_path)
tries to change the directory with a file as argument... Well, better not use chdir
in a python script, ever.
how could I get the 'my_file.bat' location?
You don't need that (and it won't suffice to execute the file). What you want is to execute the file with the current directory set to the directory of the script (making the .bat file simpler)
The root
variable, on the other hand, provides the directory where the file is located. So I'd rewrite your code like this:
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)
Adding cwd=root
allows call
to change directory to the script directory prior to execution (and only in the call), where shell=True
(your next problem) ensures that you can call a script (not a real executable) from subprocess.call
Also use lowercase comparison in case the file is called MY_FILE.BAT
. You have to love windows for all those quirks.
Upvotes: 2