ealeon
ealeon

Reputation: 12452

Determine if the program is called from a script in Python

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?

Upvotes: 0

Views: 2443

Answers (1)

JuniorCompressor
JuniorCompressor

Reputation: 20015

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

Upvotes: 5

Related Questions