0

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?

8
  • I don't know of a way to detect if the files been called from a script (In theory, it is always called by a script, be it a batch script, the command line, of your mouse double clicking on it). You could instead pass it a parameter from the script to detect with sys.argv[index] and tell it where it has been called from. Commented Mar 24, 2015 at 18:00
  • A bash script as opposed to what? Your sh script? An interactive shell? When does it matter? Commented Mar 24, 2015 at 18:01
  • 2
    Seeing if stdout is a TTY is a common, sensible check because it lets you decide whether to output in a human-readable or computer-readable format (e.g., colored output when connected to a TTY, plain output when piped to another process). But checking how your program is invoked... what would you do differently based on the identity of the parent process–and why? Commented Mar 24, 2015 at 18:01
  • from your terminal vs called from a script Commented Mar 24, 2015 at 18:01
  • 2
    I'm pretty sure the answer is no. What problem are you really trying to solve? Commented Mar 24, 2015 at 18:04

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

4 Comments

If the user's console is also bash, then this won't be able to determine if it is being run from a script or if it's run directly from the console...
i know i gave bash as an example but i want to encompasses whole script. myexe can be called from another python script or whatnot
@BillLynch can you check if the user console is bash or not and then compare against it? oh wait nvm.. hmm..
@ealeon: You can usually tell if the user console is bash by checking $SHELL. But personally, all of this is a bad idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.