Determine if the program is called from a script i

2019-09-20 14:10发布

问题:

doa

#!/bin/sh
myexe

myexe

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

OUTPUT (if i execute doa from terminal):

not from a script

OUTPUT (if i execute myexe from terminal):

not from a script

I want it to say 'from a script' if executed from doa

Question: is it possible for myexe to know that it's being executed from a bash script?

回答1:

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