How to execute python file in linux

前端 未结 7 553
长情又很酷
长情又很酷 2020-12-08 14:27

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

相关标签:
7条回答
  • 2020-12-08 14:44

    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.

    0 讨论(0)
  • 2020-12-08 14:47

    Add this at the top of your file:

    #!/usr/bin/python
    

    This is a shebang. You can read more about it on Wikipedia.

    After that, you must make the file executable via

    chmod +x your_script.py
    
    0 讨论(0)
  • 2020-12-08 14:50

    Add to top of the code,

    #!/usr/bin/python
    

    Then, run the following command on the terminal,

    chmod +x yourScriptFile
    
    0 讨论(0)
  • 2020-12-08 14:50

    If you have python 3 installed then add this line to the top of the file:

     #!/usr/bin/env python3
    

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

    For more details, follow the official forum:

    https://askubuntu.com/questions/761365/how-to-run-a-python-program-directly

    0 讨论(0)
  • 2020-12-08 14:53

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

    #! /usr/bin/python
    print('Hello, world!')
    

    2.open the terminal in that directory

    $ python hey.py
    

    or if you are using python3 then

    $ python3 hey.py
    

    0 讨论(0)
  • 2020-12-08 15:00

    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)

    0 讨论(0)
提交回复
热议问题