Making a Python script executable

后端 未结 3 1285
心在旅途
心在旅途 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:27

    Your script is running, and when it's done, it's closing. To see the results, you need to add something to stall it. Try adding this as the last line in your script:

    staller = intput("Press ENTER to close")
    
    0 讨论(0)
  • 2020-12-04 01:29

    Under Linux, you will have to make the .py file executable

    chmod 750 mypyprog.py
    

    add the proper shebang in the first line to make the shell or file explorer know the right interpreter

    #!/usr/bin/python3
    print('Meow :3')             # <- replace this by payload
    

    If you want to review the results before the shell window is closing, a staller at the end (as shown by MackM) is useful:

    input('Press any key...')
    

    As we see from the comments, you already mastered steps 1 and 2, so 3 will be your friend.

    Windows does not know about shebangs. You will have to associate the .py extension with the Python interpreter as described in the documentation. The python interpreter does not have to be in the PATH for this because the full path can be specified there.

    0 讨论(0)
  • 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?

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