In a Linux environment, everything is treated as a file, including the directories and connected devices. To run an executable file in a Linux environment, we use the terminal or the command line interface (CLI).
First, we need to place the file in a directory where we can access it and run it via the terminal. For this tutorial, we shall place it on the desktop.
Now, open the terminal, for most Linux flavors using the shortcut "Ctrl + Alt + T" should work. In case it doesn't, we can type it in the search bar and open the terminal from there.
Now, we need to navigate to the "desktop", where we have placed the python script that we wish to execute. To switch directories, we use the cd
command followed by the name of the directory.
cd <Directory Name>
As our file is placed on the desktop, we need to enter cd Desktop
in the terminal. We should see that we have shifted to the desktop directory.
Now, we need to run the python script that is placed on the desktop. To run a Python script, we need to enter the python3
command followed by the name of the file we wish to run. If our file name is "helloWorld.py", we will need to enter the following command in the terminal:
python3 helloWorld.py
If we run into an error we can replace python3
with the python
command.
Now, we should successfully be able to run the Python script in the Linux environment.
Suppose we have a file named "helloWorld.py" with the following line of code written. This file is placed in the desktop directory.
print("Hello World")
For practice, we have provided a terminal below where you can test out the commands mentioned above, we have already added and changed the directory, just execute the file.
The shebang is a special comment that we can include at the top of the Python script to specify the interpreter that should be used to execute the rest of the file.
First, add the comment on the top of the file as given below:
#!/usr/bin/env python3print("Hello, Educative!")
Make the script executable by running the following command:
chmod +x <script>.py
Execute the Python script directly from the command line or terminal:
./<script>.py
For practice, we have provided a terminal below where you can test out the commands mentioned above, we have already added a Python script named "helloEducative.py", just execute the file.
First, open the terminal, for most Linux flavors using the shortcut "Ctrl + Alt + T" should work but if it doesn't we can type it in the search bar and open the terminal from there.
To open the Python shell, we need to type the following command into the terminal:
python3
Simply, enter a line of code in python and press enter, the shell then executes the written line of code.
Now, we can write and run python codes directly from the python shell.
To exit, simply press "Ctrl + C" or enter the following command:
exit()
For practice, we have provided a terminal below where you can test out the commands mentioned above.