icon
entorSol

How To Run A Python Script In Terminal? Updated Guide 2024

One of the fundamental skills that every Python programmer should master is the ability to run Python scripts in a terminal. Whether you’re a beginner just getting started or an experienced developer looking to refine your workflow, understanding how to execute Python scripts from the command line is crucial.


In this comprehensive guide, we’ll delve into the various methods of running Python scripts in a terminal environment. We’ll explore the differences and nuances between running scripts on Windows and Linux systems, providing you with a detailed overview of the processes involved.


By the end of this guide, you’ll have a solid understanding of how to run Python scripts in different terminal environments, making you a more versatile and capable Python programmer. So, let’s dive in and learn more about how to effectively run Python scripts in a terminal!

Basic steps for Running a Python Script In Terminal (ubuntu)

ubuntu
Getting started with running Python scripts in the terminal involves mastering some basic steps. Here’s a breakdown of what you need to do:

Open a Terminal

If you’re working on a Linux or macOS system, you’ll typically find a terminal application in your applications menu or by using a system search. Some commonly used terminals include GNOME Terminal, Konsole, and Terminal on macOS.

For Windows users, you have a couple of options. You can use the Command Prompt or PowerShell. To open the Command Prompt, simply search for “cmd” or “Command Prompt” in the Start menu. Similarly, you can find PowerShell through a similar search.

These initial steps set the stage for running Python scripts from the command line interface, regardless of the operating system you’re using. Now, let’s move on to the next steps in executing Python scripts.

Navigate to Your Script’s Directory

Utilize the cd (change directory) command to navigate to the directory containing your Python script. For instance, if your script resides in a folder named “my_python_scripts,” you can navigate to it using the following command:

cd path/to/my_python_script
This command ensures that you’re in the correct directory where your Python script is located, enabling you to execute it seamlessly from the terminal. It’s an essential step in the process of running Python scripts via the command line interface.

Run the Python Script

To execute a Python script, you’ll use the python command, followed by the name of your script. For example:

python my_script.py

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

This command triggers the Python interpreter to run your script, executing the instructions contained within it. It’s the final step in the process of running Python scripts via the terminal.
Now that you’ve mastered the basics of running Python scripts in the terminal, you’re ready to explore more advanced scenarios and commands that can further enhance your Python scripting experience. Let’s delve deeper into these to broaden your skill set.

How to Run a Python Script in Linux?

linux
Running Python scripts in Linux is indeed straightforward and flexible. Here’s how you can do it:

Using Python 3

Many Linux distributions ship with both Python 2 and Python 3 installed. To ensure you’re running a Python script with Python 3, you explicitly specify Python 3 by using the python3 command instead of just python. Here’s how:
python3 my_script.py

By invoking ‘’python3’’, you ensure that your script executes with Python 3, which is the more modern and widely adopted version. This approach is essential for running Python scripts in a terminal on Linux, where Python 2 might still be available but is generally being phased out in favor of Python 3.

Using Python 3

If you have multiple versions of Python 3 installed (e.g., Python 3.8, Python 3.10, Python 3.11, Python 3.12), you can specify the version explicitly. For example, if you want to run your script using Python 3.10, you would use:

    python3.10 my_script.py

This allows you to manage and test your scripts across different versions of Python without conflicts. By default, python3 in many Linux distributions, such as Ubuntu, points to a specific version of Python 3 (e.g., Python 3.8.12). You can install other versions and call them using their specific commands, like python3.10, python3.11, or python3.12.

How to Run a Python Script in the Ubuntu Terminal

Running a Python script in the Ubuntu terminal is quite straightforward. Here’s a step-by-step guide:

1: Open the terminal: Launch the terminal application. You can typically find it in the Applications menu, or you can use the search function to locate it.
2: Navigate to the Script’s Directory: Use the cd command to navigate to the directory where your Python script is located. For example, if your script is in the “Documents” folder, you would use:
    cd Documents

3: Run the Script: Once you’re in the correct directory, you can run the Python script using the python command followed by the name of your script. For example, if your script is named “my_script.py”, you would type:

    python my_script.py
If you have both Python 2 and Python 3 installed, you might need to use python3 instead of python to specify Python 3 explicitly:
    python3 my_script.py
If you need to use a specific version of Python, you can specify it directly:
    python3.10 my_script.py
4: Execute the Script: Press Enter, and your Python script will be executed. You should see the output, if any, directly in the terminal.
That’s it! You’ve successfully run a Python script in the Ubuntu terminal. This method ensures that your script runs with the intended Python version, and allows you to manage and switch between different Python environments easily.

Running Python Scripts as Executables

Running Python scripts as executables offers convenience and flexibility. Here’s how you can make a Python script executable and run it like any other binary:
1: Add a Shebang Line: At the beginning of your Python script, include a shebang line to specify which interpreter to use. For Python 3, use:
    #!/usr/bin/env python3
And for Python 2:
    #!/usr/bin/env python
This line tells the system which interpreter to use when executing the script.
These initial steps set the groundwork for making your Python script executable. Next, let’s proceed with the remaining steps to complete the process.
2: Make the Script Executable: Employ the chmod command to grant executable permissions to your script. For instance:
    chmod +x my_script.py
This command gives the script the necessary permissions to be executed as a standalone program.
3: Run the Executable Script With the script now marked as executable, you can run it without explicitly specifying the Python interpreter:
    ./my_script.py
This method offers convenience, especially when executing your script from the terminal, as you no longer need to type python each time.
By following these steps, you can seamlessly run your Python script as if it were any other executable binary on your system. This approach streamlines the process and enhances the usability of your scripts, making them more accessible and easier to work with.

How to create and run shell scripts in linux and ubuntu?

Creating and running a shell script in Linux, including Ubuntu, is a simple process. Here’s a step-by-step guide:

Create a Shell Script

You can create a shell script using any text editor, such as nano, vim, or gedit. Here’s how to create a basic shell script using nano:

Open the Terminal

    nano my_script.sh

This will open the nano text editor with a new file named “my_script.sh”.

Write your script

    #!/bin/bash
    

# This is a simple shell script

echo "Hello, world!"

Save the file

Press Ctrl + X to exit nano, then press Y to confirm saving the changes, and finally press Enter to save the file with the same name.

Make the Script Executable

Before you can run the script, you need to make it executable. You can do this using the chmod command:
chmod +x my_script.sh
This command gives the script executable permissions.

Run the Script

Now, you can run the script by typing its name preceded by “./” to specify that it’s located in the current directory:

./my_script.sh
You should see the output “Hello, world!” printed to the terminal.
That’s it! You’ve successfully created and run a shell script in Linux or Ubuntu. You can modify the script to perform more complex tasks as needed.

How to Run Python on Windows

Windows
That’s it! You’ve successfully created and run a shell script in Linux or Ubuntu. You can modify the script to perform more complex tasks as needed.

Using Python 3

If you have Python 3 installed on your Windows machine, you can run Python scripts by following these steps:
  • Open the Command Prompt or PowerShell.
  • Navigate to the directory containing your Python script. You can do this by opening the folder where your script is located, then clicking on the address bar and typing “cmd” before hitting Enter. This will open a Command Prompt window with the directory already set.
  • Use the Python command followed by the name of your script:
    python my_script.py
  • This command triggers the Python interpreter to execute your script, allowing you to run Python code seamlessly on your Windows system.
  • These steps enable you to execute Python scripts on Windows using Python 3, providing you with a convenient way to work with Python on this platform.

Save and Run the Batch File

  • Open a text editor like Notepad.
  • Type the following command, replacing my_script.py with the name of your Python script:
    python my_script.py
  • Save the file with a .bat extension, for example, run_script.bat.
  • Double-click the batch file to execute your Python script.
This approach simplifies the process of running Python scripts on Windows by creating a shortcut that can be executed with a single click. It’s a handy method for creating simple scripts that you frequently use.

How to run a python file in vscode?

Running Python scripts in Visual Studio Code (VSCode) is convenient and efficient. Here’s how you can do it:

Open Your Python Script in VSCode

Launch VSCode and open your Python script in the editor.

Use the Integrated Terminal

VSCode provides an integrated terminal that allows you to execute commands directly within the editor. You can open it by navigating to the “Terminal” menu and selecting “New Terminal”.

Run Your Python Script

Once the integrated terminal is open, navigate to the directory where your Python script is located. You can use the cd command to change directories if needed. Then, run your Python script using the python command, as you would in a regular terminal:
python your_script.py
Replace your_script.py with the name of your Python script.
Running Python scripts within the integrated terminal of VSCode offers a seamless workflow for Python development. It allows you to write, debug, and execute your code all within the same environment, enhancing your productivity and efficiency as a developer.

Running python command line argument

Using command line arguments in Python allows you to customize script behavior dynamically. Here’s how you can implement it:

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.

By incorporating command line arguments into your Python script, you can enhance its flexibility and usability. This allows you to execute specific functions directly from the command line, streamlining your workflow and making your scripts more versatile.

Run Your Script with Command Line Arguments

In the terminal, you can execute your Python script and provide the function name as an argument:
python my_script.py function_one
This command specifies the function you want to run within your script. By passing arguments from the command line, you can dynamically control the behavior of your Python script, executing specific functions based on your requirements.
Running scripts with command line arguments offers flexibility and customization, allowing you to tailor script execution to suit different scenarios and use cases.

Handling Command Line Arguments in Python

Handling command line arguments in Python using the argparse library is a powerful way to customize script behavior. Here’s how you can do it:

Import the argparse Library

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

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.

Parse Command Line Arguments

Parse the command line arguments using the parse_args() method:
args = parser.parse_args()

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.
Handling command line arguments in Python allows you to create more versatile and interactive scripts, enabling users to customize script behavior based on their specific needs and preferences.

How to run a function in the python terminal?

To run a specific function in the Python terminal, you first need to start the Python interpreter by typing python or python3 in the terminal, depending on your Python version. Once you’re in the Python terminal, you can import the module containing your function and then call the function.
Here’s a step-by-step guide:

Open the Terminal

Launch the Terminal application on your operating system.

Start the Python Interpreter

Type python or python3 in the terminal and press Enter. This will start the Python interpreter.

Import the Module

If your function is defined in a separate module, import that module using the import statement. For example, if your function is in a module named my_module, you would type:
import my_module

Call the Function

Once the module is imported, you can call the specific function using the module name followed by the function name, and provide any necessary arguments. For example:
my_module.my_function()
If the function takes arguments, you would pass them inside the parentheses:
my_module.my_function(argument1, argument2)
If your function is defined directly in the script without being part of a module, you don’t need to import anything. Simply call the function directly.

Exit the Python Interpreter

Once you’re done working in the Python terminal, you can exit the interpreter by typing exit() and pressing Enter, or by pressing Ctrl + D.
That’s it! You’ve successfully run a function in the Python terminal.

How to Set Up and Use Virtual Environments for Python Projects?

Setting up and using virtual environments for Python projects is like creating a sandbox just for your project. Here’s why it’s useful: Imagine you have two projects—one needing Python 3.8 and another Python 3.10. Instead of managing different Python versions or cluttering your system, you create a virtual environment for each project.
Each environment has its own Python interpreter and libraries, neatly isolated from others. This way, you can work on multiple projects with different dependencies without conflicts.

To set up a virtual environment, use tools like venv or virtualenv. Once created, activate it in your terminal using source venv/bin/activate on Unix or .\venv\Scripts\activate on Windows. Now, run your Python scripts within this environment. This keeps your project dependencies contained and your system-wide Python installation clean.

Conclusion

In conclusion, running Python scripts from the terminal is a fundamental skill for Python programmers. Whether you’re on Linux, Windows, or using an integrated development environment like VSCode, the process is pretty straightforward. You can execute scripts directly, call specific functions with command line arguments, and handle different situations smoothly.

 

Ready to transform your business with top-tier custom software development solutions and It staff augmentation services? Partner with us, the premier custom software development company, where our elite team of AI and ML engineers and exceptional Python developers will bring your vision to life with precision and excellence. Let us drive your innovation and help you achieve your business goals. Contact us today!

Key takeaways to remember

  • Fundamental Skill: Running Python scripts in terminal is essential for Python programmers.
  • Basic Steps: Open terminal, navigate to script directory with cd, run script using python or python3.
    Platform-Specifics: Use python3 on Linux/MacOS; Command Prompt or PowerShell on Windows.
  • Python Version: Specify python3.10, python3.11, etc., for specific versions.
    Ubuntu Terminal: Navigate and run scripts with python or python3.
  • Executable Scripts: Add shebang line (#!/usr/bin/env python3), make the script executable with chmod +x, run with ./my_script.py.
    VSCode Usage: Open script, use integrated terminal with python.
  • Command Line Arguments: Use argparse for handling arguments.
    Virtual Environments: Create isolated environments (venv or virtualenv), activate with source venv/bin/activate or .\\venv\\Scripts\\activate.
    Shell Scripts: Create with text editors, make executable, run with ./script_name.
  • Cross-Platform Tips: Use python3 for Python 3 compatibility, batch files on Windows, VSCode’s terminal.
Mastering these steps enhances Python development by efficiently managing scripts, dependencies, and environments across different platforms.

Frequently Asked Questions

For those who prefer not to install libraries globally, setting up a virtual environment is an excellent solution. Virtual environments allow you to create isolated environments for your projects, each with its own set of installed libraries and Python versions. This way, you can work on multiple projects with different dependencies without conflicts.

Virtual environments are isolated environments that allow you to manage dependencies for different projects separately. Each virtual environment has its own set of installed libraries and can have different Python versions, preventing conflicts between project dependencies.
You can create a virtual environment using venv or virtualenv. To create a virtual environment, run the following command

python -m venv myenv

or with virtualenv:

virtualenv myenv
To activate a virtual environment, use the following commands:

Yes, after activating the virtual environment, you can run your Python scripts within this isolated environment. This ensures that your project’s dependencies are contained and do not interfere with other projects or the system-wide Python installation.
Using virtual environments helps in managing dependencies for different projects without conflicts. It ensures that each project has its own isolated environment, allowing you to use different libraries and Python versions for different projects. This setup prevents dependency issues and keeps your system-wide Python installation clean.