Reputation: 28030
I am using a windows batch file to run a python script. The code is below;
start pythonw "C:\Users\XXX\Workplace\python_script.py"
This is undesirable because the path of the python script is absolute. Suppose I put the batch file and the python script in the same folder. How to write the batch file to somehow detect the current folder and run the python script which is in the same folder?
Thank you.
Upvotes: 1
Views: 4901
Reputation: 79983
Since you can run pythonw
without specifying its directory, then pythonw
must be located on the path.
If you then place yourbatch.bat in the same directory, then it follows that yourbatch.bat is also on the path, so all you'd need to do is execute yourbatch and your batch will run.
The directory from which your batch is executed is not relevant. If you change your batch to
start "Window title" pythonw "python_script.py"
and place that in your path then yourbatch will run pythonw
using parameter "python_script.py"
from the current directory.
Note: the start
command appreciates a "window title" as its first quoted argument. You don't want a window title? Just use ""
.
If you have your python script in the same directory as yourbatch.bat then
start "Window title" pythonw "%~dp0\python_script.py"
should run that script wherever it is.
and for a really flexible approach
start "Window title" pythonw "%~1.py"
Would start the script somename.py
if you execute
yourbatch somename
where somename
may be quoted and may contain any path you like (like "c:\my development\area\latest_script"
for instance)
Upvotes: 3
Reputation: 6032
You can use %~dp0
to get the path to the foldet in which the bat file is located.
The code will look like this;
start pythonw "%~dp0\python_script.py"
Upvotes: 2