Skip to content Skip to sidebar Skip to footer

How To Execute Python File In Linux

I am using linux mint, and to run a python file I have to type in the terminal: python [file path], so is there way to make the file executable, and make it run the python command

Solution 1:

You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.

It should look like that :

#!/usr/bin/env python

or the real path

#!/usr/bin/python

You should also check the file have the right to be execute. chmod +x file.py

As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)

Solution 2:

I suggest that you add

#!/usr/bin/env python

instead of #!/usr/bin/python at the top of the file. The reason for this is that the python installation may be in different folders in different distros or different computers. By using env you make sure that the system finds python and delegates the script's execution to it.

As said before to make the script executable, something like:

chmod u+x name_of_script.py

should do.

Solution 3:

yes there is. add

#!/usr/bin/env python

to the beginning of the file and do

chmod u+rx <file>

assuming your user owns the file, otherwise maybe adjust the group or world permissions.

.py files under windows are associated with python as the program to run when opening them just like MS word is run when opening a .docx for example.

Solution 4:

1.save your file name as hey.py with the below given hello world script

#! /usr/bin/pythonprint('Hello, world!')

2.open the terminal in that directory

$ python hey.py

or if you are using python3 then

$ python3 hey.py

Solution 5:

Add to top of the code,

#!/usr/bin/python

Then, run the following command on the terminal,

chmod +x yourScriptFile

Post a Comment for "How To Execute Python File In Linux"