How to Run Python Script Linux (Ubuntu) Command Line
You can run Python scripts through the Linux command line. This is a great feature of Linux-based operating systems like Ubuntu or Linux Mint. You can easily run or compile Python files directly without needing to install any specialized IDE for Python development.
Not only can you run Python files, but you can also interpret Python statements directly in the terminal.
How to Create a Python File Using Linux Terminal
- Open the terminal using Ctrl + Alt + T.
- Use any text editor to create a Python file named
file_name.py
. For example:- If you have Sublime Text Editor, use the command:
subl file_name.py
- If you don't have Sublime Text, use the default text editor (e.g., Gedit in Ubuntu) with the command:
gedit file_name.py
- If you have Sublime Text Editor, use the command:
Write your Python code in the editor and save the file.
How to Run a Python File Using Linux Terminal
- Open the terminal using Ctrl + Alt + T.
- Check the current directory of the terminal using the command:
pwd
- Navigate to the directory containing your Python file. For example, if the file is in
/home/you/Desktop
, use the command:cd /home/you/Desktop
- Run the Python file with the command:
python file_name.py
The terminal will display the output of your Python script.
How to Write and Run Python Code Directly in the Terminal
- Open the terminal using Ctrl + Alt + T.
- Type
python
and press Enter to start the Python interpreter. - Write your Python code line by line, pressing Enter after each statement to execute it.
Tips for Writing Python Code in the Terminal
- To copy and paste in the terminal, use Ctrl + Shift + C to copy and Ctrl + Shift + V to paste.
- Pay attention to indentation, which is crucial in Python. Use two spaces or the Tab key as needed for proper indentation.
Fun with Python in the Terminal
- Try simple calculations:
>> 8 + 3
. Press Enter to see the result. - Create a list:
>> list = [3, 4, 2, 5]
. Then typelist
and press Enter to display it.
Did you find this article helpful? Let us know in the comments!