Close Up Photo of Programming of Codes
|

4 Ways to Run Python Commands from Terminal

You can run Python commands from your terminal or command prompt. Since Python is an interpreted language, you don’t have to compile it before doing so.

But you could do it in several different ways. Each has its merits, so they work well in one instance and not in the other.

Grab your aromatic coffee (or tea) and get ready…!

1. Python REPL: the beginner-friendly way to run Python commands

REPL stands for Read-Evaluate-Pring-Loop. As it suggests, the REPL environment will evaluate each line you enter and print its results immediately on the terminal.

 

Screenshot from 2022-06-23 08-19-38

 

When you’re learning Python, you’d almost always use a REPL. It’s the easiest way to execute Python commands.

Just type “python” on the terminal. It’ll take you to an interpreter environment. This is where you’d probably write your print ("Hello World!")

REPLs are very powerful. Even the most experienced still use REPLs to test out various aspects of their application.

For instance, Django developers use the shell to test out database queries for their apps. Most data scientists use Jupyter Notebooks, an evolved version of REPLs.

python manage.py shell # To get a Django shell
Bash

The notable advantage of REPLs is that we don’t have to wait until the entire program evaluates. You could run the command and see the output then and there.

Yet, there are instances where we don’t even want to go into a different environment. The following method comes in handy in many ways.

2. Run the Python command from the terminal and get output instantly.

There are instances where you need to execute some Python commands instantly. Going into a REPL won’t take much time. But there is a better way to do this.

You can use the “-c” option to follow up with a command to execute. I use this very often to generate secret tokens. The following Python command generates a random token of 64 characters.

python -c "import secrets; print(secrets.token_urlsafe(64))"
Bash

 

Screenshot from 2022-06-23 08-23-52

 

I use this one very often to generate secure passwords quickly.

Since Python is a very concise language, these sorts of one-liners are prevalent. As a programmer, you’ll have many instances where you need to execute Python scripts on the go.

3. Run a Python script in the terminal

You can run Python scripts on the terminal in two ways. First, you can type Python (or Python3) followed by the path to your script file. The second option is you can make the Python script file an executable.

The easiest is to use the first one. You could also change the Python interpreter without editing the script file.

python hello.py
>> Hello, world!
Bash

Yet, if you use the script often and the interpreter remains the same, the best option is an executable. You can specify the interpreter path at the top of the page, as shown below.

#! /usr/bin/python

print("Hello, world!")
Python

Then you have to make the script executable by running the following command on your terminal.

sudo chmod +x hello.py
Python

Now, you don’t have to type in Python every time.

./hello.py

>> Hello world
Bash

The second method has an additional drawback. If you’re sharing your code with a different person, your script will expect the Python interpreter in the exact location. This may not be the case on another person’s PC.

4. Create a CLI and run Python scripts on the command line.

You’d want to create a CLI for more advanced repetitive use cases. A CLI allows you to have more control over your script.

One of the benefits is that you can run a Python script with arguments. You could also have this on an executable f le. You could use “argparser” to get the value of command-line inputs. But the method described here is more convenient and powerful.

We use Typer’s Python library to convert our scripts into CLI.

The creators of the emerging modern web framework, FastAPI, created Ty er. They call it the little sibling of Fast API.

If your Python function has type hints, with Typer and a few tweaks, you can make it a CLI app. Here’s a basic example.

import typer

app = typer.Typer()

@app.command()
def main(name: str):
    """
    Hello World
    """
    print(f"Hello {name}")

if __name__ == "__main__":
    app()
Bash

 

Screenshot from 2022-06-24 05-29-19

 

You can do a lot more with Typer. I use it very often, and it helps me stay productive in many ways.

You could read more about Typer in my previous post, How to Create Interactive CLIs in Python?

Final thoughts

Running a Python command on a terminal is easier than running other programs. Since Python is an interpreted language and needs no compilation, even newbies find it straightforward.
But there are different ways you could run a Python command. You could run it with Python, make the file an extension, or even make it a CLI.

Did you know, like you run Python commands from a terminal, you could also run shell commands in Python?


Thanks for the read, friend. It seems you and I have lots of common interests. Say Hi to me on LinkedIn, Twitter, and Medium.

Not a Medium member yet? Please use this link to become a member because I earn a commission for referring at no extra cost for you.

Similar Posts