Excute script only from another file

Chris Angelico rosuav at gmail.com
Mon Nov 25 04:15:38 CET 2013


On Mon, Nov 25, 2013 at 12:55 PM, Himanshu Garg <hgarg.india at gmail.com> wrote:
> I want that a script should only be executed when it is called from another script and should not be directly executable through linux command line.
>
> Like, I have two scripts "scrip1.py" and "script2.py"  and there is a line in "script1.py" to call "script2.py" as subprocess.call(["python", "script2.py"]).
>
> Then this is should call script2 but I should not be able to directly call script2 as $python script2.py

Easy! Just have your subprocess.call pass a special argument, which
you then look for in script2:

subprocess.call(["python", "script2.py","confirm"])

# script2.py
import sys
if "confirm" not in sys.argv:
    print("This script should not be run directly.")
    sys.exit(1)

# rest of script2.py follows

ChrisA



More information about the Python-list mailing list