简体   繁体   中英

How to open a python file on a separate drive via batch file?

I have a .py and a batch file on a usb drive. How can i get it so that the batch file can open the .py file. When I have tried this before it cannot locate the file.

Suppose the Python file is called script.py and the batch file is not only on the same drive, but also in the same folder. Then the command would be:

"%~dp0script.py"

Let's break this down:

'%~0' in a batch script is path/filename of the currently executing script. You can add modifiers to get parts of the path/filename: 'd' is the drive letter, and 'p' is the directory path (which includes a trailing slash), so '%~dp0' is drive and path (but not the filename or extension) of the currently executing script. For more information on this syntax, type "help call" into a command window.

Since I assumed the python script was in the same folder, you merely add the script name to '%~dp0'. If you are executing f:\\path\\to\\batchfile.bat, "%~dp0script.py" becomes "f:\\path\\to\\script.py". If the script is in a subfolder you can add that in - "%~dp0subfolder\\script.py" or even "%~dp0..\\sibling\\script.py" if the python script is in a sibling folder to the one your batch script is running from.

Finally, for good measure you quote the whole thing in case the path portion contains spaces. If your python script requires arguments you can add them afterwards, outside the quotes.

"%~dp0script.py" "arg1" "arg2" "arg3" ...

The nice thing about all this is that this works whether your pair of files are on a USB drive, local subfoler, CD or DVD, and if the user copies both scripts together to some other local folder = together anywhere on their computer - the batch script still calls the python script without having to be changed. It also does not require the user or your script to "cd" to the folder containing the script first - it works regardless of the working directory when your batch file is invoked by the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM