Shebang line


To run python programmes from command line, first line of the python program should be Shebang line.

Shebang line for windows is
#! python3

Lets see an example, I opened notepad and wrote the following code and then saved it in as "F:\Python Codes\hello.py" with the file format as All Files

Then I opened the command prompt by typing cmd in search bar

The command prompt autocompletes the file location if I press tab.
I could have used python.exe instead of py in the start.

I could run the same code using 'run' which opens by pressing the windows button and R

But the problem with it is that it run the code and immediately after the code is run, the command prompt closes itself. That is I see window pop up and immediately close itself.

A pause.exe comes with windows to pause the command.

Batch File

A batch file is a file containing multiple command line commands to be executed at once. This is known as shell file in other operating systems.

Batch file ends with a .bat extension.

I wrote the above code and saved it with a .bat extension with the file types as 'All Files', in the location F:\hello.bat

The @ symbol tells to not put these lines in the output.
The %* tells to forward any command line arguments to the python code

Let's run that batch file.

We don't need Double Quotation marks(") around the location as there are no space somewhere in between. Notice we use backword slash \ in the command prompt and Run for locating the files instead of forward slash /
We don't need to write that .bat in the end. Run automatically assumes that the file is batch file

And we get the output!

But what if we wanted to run the script in the background without opening any window? We can do that by getting rid of pause and writing pyw instead of just py. That runs a windowless python.

pyw F:\hello.bat %*

That will run the script 'hello.bat' windowless without any flickring

We can set the folder of the batch to environment variable and by just typing the file name, we can run the program

Command line arguments

command line argumnets are specified when running

Command line arguments can be accessed by using the sys.argv variable

In [1]:
import sys
print(sys.argv)
['C:\\Users\\there\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py', '-f', 'C:\\Users\\there\\AppData\\Roaming\\jupyter\\runtime\\kernel-5bcb559b-9db9-463a-bae6-3ddf7d8ff84c.json']

Let's go back to the hello file in notepad

Running that batch file from run

And the output:

And that is why we need the %* because the argument are being passed to that python file