Determine if the program is called from a script in Python

后端 未结 1 449
青春惊慌失措
青春惊慌失措 2021-01-29 07:37

doa

#!/bin/sh
myexe

myexe

if sys.stdout.isatty():
    print \'from a script\'
else:
    print \'not from a script\'


        
相关标签:
1条回答
  • 2021-01-29 08:20

    You can use psutil to ask for the name of the process with id the parent process id:

    import psutil
    import os
    
    ppid = os.getppid() # Get parent process id
    psutil.Process(ppid).name() == "bash"
    

    You can install psutil with pip command:

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