1

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 .

Cœur
  • 37,241
  • 25
  • 195
  • 267
Natesh bhat
  • 12,274
  • 10
  • 84
  • 125

2 Answers2

4

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
iBug
  • 35,554
  • 7
  • 89
  • 134
  • i dont want a command line argument way since i don't know what scripts will call python file later , – Natesh bhat May 11 '18 at 01:57
  • 1
    Using a command line argument would be a much cleaner and easier-to-debug way to do thing (IMHO). It would frustrate me to be debugging the behaviour of a python script and figure out that its behaviour changes when run from a script vs by a user directly. Having programs behave the same way regardless of the invocation method is extremely valuable. – John Moon May 11 '18 at 02:01
3

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.

o11c
  • 15,265
  • 4
  • 50
  • 75