• Python
  • 5 MINUTES READ

How To Run A Python Script In Terminal?

  • POSTED ON
  • October 27, 2023
  • POSTED BY
  • Muhammad Jalees
  • POSTED ON October 27, 2023
  • POSTED BY Muhammad Jalees

One of the essential skills every Python programmer should have is the ability to run Python scripts in a terminal. In this comprehensive guide, we’ll cover various ways to run Python scripts in a terminal and explore different scenarios, including running Python on Windows and executing Python scripts in Linux. Let’s learn more about how

One of the essential skills every Python programmer should have is the ability to run Python scripts in a terminal. In this comprehensive guide, we’ll cover various ways to run Python scripts in a terminal and explore different scenarios, including running Python on Windows and executing Python scripts in Linux. Let’s learn more about how to run a python script in terminal?

Running Python Scripts in Terminal: The Basics

To ace the process of how to run a python script in terminal, you’ll need to follow these fundamental steps:

1. Open a Terminal:

If you’re using a Linux or macOS system, you can usually find a terminal application in your applications or through a system search. Commonly used open terminal python include the GNOME Terminal, Konsole, and macOS’s Terminal.

On Windows, you can use the Command Prompt or PowerShell. You can find the Command Prompt by searching for “cmd” or “Command Prompt” in the Start menu, while PowerShell can be found similarly.

2. Navigate to Your Script’s Directory:

Use the cd (change directory) command to navigate to the directory where your Python script is located. For example, if your script is in a folder called “my_python_scripts,” you can navigate to it like this while learning how to run a python script in terminal

cd path/to/my_python_scripts

3. Run the Python Script:

To run a Python script, use the Python command, followed by the name of your script. For instance:

python my_script.py

Replace “my_script.py” with the actual name of your Python script.

Now that you’ve got the basics down, let’s delve deeper into some specific scenarios and commands that can enhance your Python scripting experience.

How to run a python script in Linux?

Linux is a favorite platform for developers, and running Python scripts is straightforward.

Using Python 3

Many Linux distributions come with both Python 2 and Python 3 installed. To run a Python script using Python 3, you can explicitly specify Python 3 by using the python3 command instead of Python. For example:

python3 my_script.py

this ensures that your script runs with Python 3, which is the more modern and widely used way for learning how to run a python script in terminal.

Running Python Scripts as Executables

You can make a Python script executable and run it like any other binary. Here are the steps to follow:

1. Add a Shebang Line:

At the beginning of your Python script, add a shebang line to specify which interpreter to use. For Python 3, the shebang line would be:

#!/usr/bin/env python3

For Python 2, you can use:

#!/usr/bin/env python

2. Make the Script Executable:

Use the chmod command to make your script executable. For example:

chmod +x my_script.py

3. Run the Executable Script:

Now, you can run your script without specifying the Python interpreter:

./my_script.py

This method is convenient, especially when you want to run your script from the terminal without typing Python each time.

How to Run Python on Windows

Running Python scripts on Windows is slightly different but equally straightforward.

1. Using Python 3

If you have Python 3 installed on your Windows machine, you can run Python scripts by opening the Command Prompt or PowerShell and using the Python command:

python my_script.py

2. Save and Run the Batch File:

Save the batch file and double-click it to run your Python script.

This approach allows you to create simple scripts that can be executed with a single click on Windows.

How to run a python file in vscode?

Visual Studio Code (VSCode) is a popular code editor, and many Python developers use it for their projects. If you’re using VSCode, you can run Python scripts directly from the editor.

1. Open Your Python Script in VSCode:

Launch VSCode and open your Python script.

2. Use the Integrated Terminal:

In VSCode, there is an integrated terminal available. You can open it by going to the “Terminal” menu and selecting “New Terminal.”

3. Run Your Python Script:

In the integrated terminal, navigate to the directory where your Python script is located, and then run your script using the python command, as previously explained.

Using the integrated terminal in VSCode is a convenient way to work on and run your Python scripts without leaving your code editor.

Running python command line argument

Sometimes, you may want to run a specific function from your Python script directly from the command line. To do this, you can use command line arguments.

1. Modify Your Python Script:

Update your Python script to accept command line arguments and execute the desired function. You can use Python’s argparse library to parse command line arguments efficiently.

Here’s an example of how to create a Python script that accepts command line arguments to call a specific function:

import argparse

def function_one():
    print("Function One")

def function_two():
    print("Function Two")

if _ _name _ _ == "_ _main_ _ ":
     parser = argparse.ArgumentParser(description="Run a specific function.")
     parser.add_argument("function", choices=["function_one", "function_two"]

     args = parser.parse_args()

     if args.function == "function_one":
         function_one()
     elif args.function == "function_two":
         function_two()

In this example, the script accepts a function argument to specify which function to run.

2. Run Your Script with Command Line Arguments:

In the terminal, run your Python script and provide the function name as an argument:

python my_script.py function_one

This way, you can run specific functions within your script based on your requirements.

Handling Command Line Arguments in Python

In addition to running specific functions, Python scripts can accept and process command line arguments to customize their behavior. Here’s how to handle command line arguments in Python using the argparse library:

1. Import the argparse Library:

At the beginning of your Python script, import the argparse library:

import argparse

2. Define Argument Parsing:

Create an argument parser object and define the arguments you want to accept. For example:

parser = argparse.ArgumentParser(description="Description of your script.")
parser.add_argument("arg1", type=int, help="Description of argument 1")
parser.add_argument("--arg2", type=float, help="Description of argument 2",

In this example, we define two arguments, one positional (arg1) and one optional (–arg2) with a default value.

3. Parse Command Line Arguments:

Parse the command line arguments using the parse_args() method:

args = parser.parse_args()

4. Access Argument Values:

You can access the values of the arguments using the args object. For example:

print("arg1", args.arg1)
print("arg2", args.arg2)

Now, when you run your Python script in the terminal, you can provide the specified arguments, and your script will process them accordingly.

Conclusion

Executing a Python script within a terminal is an essential skill for every Python programmer. Whether you’re using Linux, Windows, or an integrated development environment like VSCode, the process is straightforward. You can run Python scripts as executables, call specific functions with command line arguments, and handle various scenarios effectively.

In summary, here are the key takeaways:

To execute a Python script, first open a terminal, then navigate to the directory where the script is located, and finally, run the script using the ‘python’ command followed by the script’s name.

On Linux, consider using python3 to ensure you’re using Python 3.

On Windows, make Python scripts executable using batch files for easy execution.

In VSCode, leverage the integrated terminal to execute Python scripts seamlessly within the editor.

Modify your Python scripts to accept command line arguments and run specific functions as needed.

By mastering these techniques, you’ll have the skills needed to run Python scripts effectively in various environments and scenarios. Happy coding!

ABOUT THE AUTHOR

Muhammad Jalees

Regulations can present a big challenge for fintech product managers. Build compliance into your development process from the start, with these tips from a leading financial product manager. Regulations can present a big challenge for fintech product managers.

More Related Article
We provide tips and advice on delivering excellent customer service, engaging your customers, and building a customer-centric business.