How to determine if Python script was run via command line?

前端 未结 11 1703
心在旅途
心在旅途 2020-12-15 03:58

Background

I would like my Python script to pause before exiting using something similar to:

raw_input(\"Press enter to close.\")

but

11条回答
  •  眼角桃花
    2020-12-15 04:51

    Okay, the easiest way I found and made was to simply run the program in the command line, even if it was ran in the Python IDLE.

    exist = lambda x: os.path.exists(x)    ## Doesn't matter
    
    if __name__ == '__main__':
    
        fname = "SomeRandomFileName"    ## Random default file name
    
        if exist(fname)==False:         ## exist() is a pre-defined lambda function
            jot(fname)                  ## jot() is a function that creates a blank file
            os.system('start YourProgram.py')    ## << Insert your program name here
            os.system('exit'); sys.exit()   ## Exits current shell (Either IDLE or CMD)
    
        os.system('color a')            ## Makes it look cool! :p
        main()                          ## Runs your code
        os.system("del %s" % fname)     ## Deletes file name for next time
    

    Add this to the bottom of your script and once ran from either IDLE or Command Prompt, it will create a file, re-run the program in the CMD, and exits the first instance. Hope that helps! :)

提交回复
热议问题