What is the best way to call a script from another script?


Question

I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.

For example:

File test1.py

print "I am a test"
print "see! I do nothing productive."

File service.py

# Lots of stuff here
test1.py # do whatever is in test1.py

I'm aware of one method which is opening the file, reading the contents, and basically eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.

1
265
5/7/2019 7:15:44 AM

Accepted Answer

The usual way to do this is something like the following.

test1.py

def some_func():
    print 'in test 1, unproductive'

if __name__ == '__main__':
    # test1.py executed as script
    # do something
    some_func()

service.py

import test1

def service_func():
    print 'service func'

if __name__ == '__main__':
    # service.py executed as script
    # do something
    service_func()
    test1.some_func()
246
7/27/2009 7:12:30 AM

This is possible in Python 2 using

execfile("test2.py")

See the documentation for the handling of namespaces, if important in your case.

In Python 3, this is possible using (thanks to @fantastory)

exec(open("test2.py").read());

However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon