Excute script only from another file

Peter Otten __peter__ at web.de
Mon Nov 25 09:12:22 CET 2013


Himanshu Garg 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

Put the toplevel code into a function, i. e. change

#script2.py old
print "hello from script2"

to

# script2.py new

def f(): # you should pick a descriptive name instead of f
    print "hello from script2"

and then import it from script1 and invoke the function:

# script1.py old
#...
subprocess.call("python", "script2.py")
#...

# script1.py new
import script1
#...
script.f()
#...






More information about the Python-list mailing list