The .bat file:
@py C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\TestProgram(.bat batch file and shebang line usecase).py %*
@pause
The .py file:
#! python3
print('Hello World, this is a test program for showing the use of .bat batch files, and the role of the shebang line.')
When I run the .bat file in PowerShell or Command Prompt:
PS C:\Users\Universal Sysytem> py "C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\BatchFile-TestProgram.bat"
File "C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\BatchFile-TestProgram.bat", line 1
@py C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\TestProgram(.bat batch file and shebang line usecase).py %*
^
SyntaxError: invalid syntax
P.S:
- The respective paths to the respective files (.py and .bat) do not have any errors.
- I also tried
@py.exeinstead of@py - In Environment Variables, the PATH variable is also set accordingly
- I also tried removing %* from inside the .py file
- Reference: Book: Automate the Boring Stuff with Python (Appendix B)
Guys, I finally solved it! Thank you so much, everybody, who answered my question or gave feedback through comments! I am very grateful for your valuable time in trying to help a noob like me. Thank you!:)
Okay, so the solution:
First of all, I made a slight change to my .bat file/batch file. I enclosed the path to the .py file in double-quotes("):
Finally, instead of running the .bat file with py at the beginning of its location's path, I just ran the .bat file. In my PowerShell, I moved to the directory of the .bat file and then just ran the .bat file:
It returned the correct output:
Also, I was able to run the batch file from the Run Dialog (WIN + R). The output was the same as running the batch file directly in PowerShell. I just entered the complete path to the batch file, enclosing it in double-quotes:
What I learned:
pyexecutes files written in Python. It doesn't execute .bat files because Python interpreter does not understand CMD syntax in which the .bat file is written.