Executando Código Python no Terminal do Ubuntu, Debian e Derivados

3 min read 4 months ago
Published on Aug 16, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through the process of running Python scripts directly in the terminal on Ubuntu, Debian, and their derivatives. Whether you're a beginner or looking to enhance your coding skills, executing code in the terminal is a fundamental skill for any Python developer.

Step 1: Install Python

Before you can run Python scripts, ensure that Python is installed on your system.

  1. Open your terminal.
  2. Check if Python is installed by entering the following command:
    python3 --version
    
    • If Python is installed, you’ll see the version number.
    • If not installed, you can install it by running:
    sudo apt update
    sudo apt install python3
    

Step 2: Write Your Python Script

Create a Python script that you want to execute.

  1. Open a text editor (like nano or vim) in the terminal:
    nano my_script.py
    
  2. Write your Python code. For example:
    print("Hello, World!")
    
  3. Save and exit the editor (in nano, press CTRL + X, then Y to confirm).

Step 3: Execute the Python Script

Now that your script is ready, you can run it from the terminal.

  1. In the terminal, navigate to the directory where your script is saved. Use the cd command:
    cd path/to/your/script
    
  2. Run your script using Python:
    python3 my_script.py
    

Step 4: Running Python Code Interactively

You can also run Python commands directly in the terminal without creating a script.

  1. Enter the Python interactive shell by typing:
    python3
    
  2. You can now execute Python commands directly. For example:
    print("Hello, Interactive World!")
    
  3. Exit the interactive shell by typing exit() or pressing CTRL + D.

Practical Tips

  • Use chmod +x my_script.py to make your script executable.
  • You can run your script without explicitly calling Python if you add a shebang line at the top of your script:
    #!/usr/bin/env python3
    

Common Pitfalls

  • Ensure you're using python3 instead of python, as many systems may have Python 2 installed by default.
  • If you receive a "command not found" error, double-check your installation and ensure Python is correctly added to your system's PATH.

Conclusion

You've learned how to install Python, write and execute scripts in the terminal on Ubuntu and Debian. Mastering these basics will help you build more complex projects and streamline your coding workflow. For further learning, consider exploring virtual environments or more advanced Python features. Happy coding!