Natesh bhat
Natesh bhat

Reputation: 13192

How to check if a script is being called from terminal or from another script

I am writing a python script and i want to execute some code only if the python script is being run directly from terminal and not from any another script.

How to do this in Ubuntu without using any extra command line arguments .?

The answer in here DOESN't WORK: Determine if the program is called from a script in Python

Here's my directory structure

home |-testpython.py |-script.sh

script.py contains

./testpython.py

when I run ./script.sh i want one thing to happen . when I run ./testpython.py directly from terminal without calling the "script.sh" i want something else to happen .

how do i detect such a difference in the calling way . Getting the parent process name always returns "bash" itself .

Upvotes: 1

Views: 1928

Answers (2)

iBug
iBug

Reputation: 37217

I recommend using command-line arguments.

script.sh

./testpython.py --from-script

testpython.py

import sys
if "--from-script" in sys.argv:
    # From script
else:
    # Not from script

Upvotes: 4

o11c
o11c

Reputation: 16016

You should probably be using command-line arguments instead, but this is doable. Simply check if the current process is the process group leader:

$ sh -c 'echo shell $$; python3 -c "import os; print(os.getpid.__name__, os.getpid()); print(os.getpgid.__name__, os.getpgid(0)); print(os.getsid.__name__, os.getsid(0))"'
shell 17873
getpid 17874
getpgid 17873
getsid 17122

Here, sh is the process group leader, and python3 is a process in that group because it is forked from sh.

Note that all processes in a pipeline are in the same process group and the leftmost is the leader.

Upvotes: 3

Related Questions