0

I'm trying to convert my python code into bat file.

I used the following guide: https://datatofish.com/batch-python-script/ but the problem it relies on pathes from my own computer, and when i sent it to someone else he wasn't able to run it.

this is what i put in my txt file:

"C:\Users\Adi Portal\AppData\Local\Programs\Python\Python37\python.exe" "C:\Users\Adi Portal\PycharmProjects\War_Management_Project\CompanyCommander.py"
pause

I would like to know what should i change in the txt file so other people can run it in their computer.

Adi Portal
  • 55
  • 6

1 Answers1

2

If you can count on them having installed Python globally (with admin privileges) and that the .bat file will be in the same directory as the .py file, you can use:

py.exe -3 "%~dp0\CompanyCommander.py"

py.exe is the Windows launcher that is stored in a common location and can find installed copies of Python. -3 tells it to run the latest installed version of Python 3 available. %~dp0 is the drive & path containing the batch script, so if the Python file is in the same directory, it will be found.

Note that thanks to the Windows launcher, you may not need to use a .bat file at all. If Python was installed with admin privileges and associated with the .py extension, then all you need is a UNIX-style shebang line at the top:

#!/usr/bin/env python3

and to add a line at the very end of the script:

input("Press enter to exit...")

The Windows launcher recognizes shebang lines and handles them appropriately, and the input function will provide the same basic functionality as a batch script's pause.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Do you happen to know where needing the shebang line is documented? I had thought on windows you didn't even need that much, that the extension was enough to run the script. – Anon Coward Sep 06 '19 at 21:49
  • @AnonCoward: You want the shebang line to explicitly specify the Python version (and bonus, make portable scripts work on both Windows and UNIX-likes); the OP was explicitly launching using Python 3 in their original attempt, so a shebang makes it clear it's intended for Python 3, even if omitting the shebang line would launch the most recent version of Python anyway. It's not critical, but I prefer to include it for the portability reasons (and to be in the habit in case I'm working with Py2 scripts where the shebang *is* necessary on Windows). – ShadowRanger Sep 07 '19 at 00:07