Executando Código Python no Terminal do Ubuntu, Debian e Derivados
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.
- Open your terminal.
- 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.
- Open a text editor (like nano or vim) in the terminal:
nano my_script.py
- Write your Python code. For example:
print("Hello, World!")
- Save and exit the editor (in nano, press
CTRL + X
, thenY
to confirm).
Step 3: Execute the Python Script
Now that your script is ready, you can run it from the terminal.
- In the terminal, navigate to the directory where your script is saved. Use the
cd
command:cd path/to/your/script
- 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.
- Enter the Python interactive shell by typing:
python3
- You can now execute Python commands directly. For example:
print("Hello, Interactive World!")
- Exit the interactive shell by typing
exit()
or pressingCTRL + 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 ofpython
, 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!