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

前端 未结 11 1715
心在旅途
心在旅途 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:43

    From the idea behind this answer, adding for Win10 compatibility (Ripped from Python 2.7 script; modify as needed):

    import os, psutil
    status = 1
    if __name__ =="__main__":
        status = MainFunc(args)
        args = sys.argv
        running_windowed = False
        running_from = psutil.Process(os.getpid()).parent().name()
        if running_from == 'explorer.exe':
            args.append([DEFAULT OR DOUBLE CLICK ARGS HERE])
            running_windowed = True
        if running_windowed:
            print('Completed. Exit status of {}'.format(status))
            ready = raw_input('Press Enter To Close')
        sys.exit(status)
    

    There is a number of switch like statements you could add to be more universal or handle different defaults.

提交回复
热议问题