Reputation: 171
I am trying to run a batch file through python; however, it is not recognizing the path. It stops reading the path after the space between 'Practice' and 'Folder'. How can I fix this? I've tried the r and using forward and backward slashes. Any help would be awesome. Thank you!
import os
Practice = r"C:\Users\Username\Desktop\Practice Folder\Practice.bat"
os.system(Practice)
'C:\Users\Username\Desktop\Practice' is not recognized as an internal or external command, operable program or batch file.
Upvotes: 2
Views: 3939
Reputation: 3036
Try using call
from subprocess
module.
You need to enclose the command only in double quotes.
from subprocess import call
call(r'"C:\Users\Username\Desktop\Practice Folder\Practice.bat"')
(Notice the order of placing quotes...)
This would even work with os.system()
provided you take care the order of quotation marks.
from os import system
system(r'"C:\Users\Username\Desktop\Practice Folder\Practice.bat"')
This should help fix your problem.
Upvotes: 2
Reputation: 5372
Change working directory to the script directory as you are using some relative redirection paths. Pushd changes current directory to any drive and can map network drives. The &&
chains commands and only runs the right hand command if the left hand command succeeds. %UserProfile%
is a standard environmental variable which is usually better then using a fixed path of C:\Users\Username
.
import os
Practice = r'pushd "%UserProfile%\Desktop\Practice Folder" && Practice.bat'
os.system(Practice)
Upvotes: 1
Reputation: 3054
Try this
import os
Practice = os.path.abspath(r"C:\Users\Username\Desktop\Practice Folder\Practice.bat")
Edit:
Something like this worked for me
os.system(r'"C:\Users\Username\Desktop\Practice Folder\Practice.bat"')
Upvotes: 0
Reputation: 2981
You probably need to use two types of quotation marks e.g.
import os
Practice = r"'C:\Users\Username\Desktop\Practice Folder\Practice.bat'"
os.system(Practice)
As it is, your string does not contain quotation marks - you need to include quotation marks within your string or else Windows will think that Folder\Practice.bat
is an argument to the command rather than a continuation of the file path
Upvotes: 0