Making a Python script executable

后端 未结 3 1296
心在旅途
心在旅途 2020-12-04 00:45

Suppose I have a Python script, that I want to run by executing outside of the command line, just by double clicking it in the file explorer. When I double click a .py

3条回答
  •  孤城傲影
    2020-12-04 01:33

    Im pretty sure the proper way to do this would be something like

    #somefile.py
    
    def some_definition_you_want_to_run():
        print("This will print, when double clicking somefile.py")
    
    #and then at the bottom of your .py do this
    if __name__ == "__main__":
         some_definition_you_want_to_run()
         #next line is optional if you dont "believe" it actually ran 
         #input("Press enter to continue")
    

    this makes it so anything that is under the if statement happens when opening it from outside (not when you import it, because "name" doesnt == "main" at that time)

    To run it, simply double click it. and BOOM it runs.

    I dont have enough linux familiarity to confirm this is how it works on linux, but it definitely works on windows. Anyone else confirm this?

提交回复
热议问题