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
:
JavaScript
x
3
1
print "I am a test"
2
print "see! I do nothing productive."
3
File service.py
:
JavaScript
1
3
1
# Lots of stuff here
2
test1.py # do whatever is in test1.py
3
I’m aware of one method which is opening the file, reading the contents, and basically evaluating it. I’m assuming there’s a better way of doing this. Or at least I hope so.
Advertisement
Answer
The usual way to do this is something like the following.
test1.py
JavaScript
1
8
1
def some_func():
2
print 'in test 1, unproductive'
3
4
if __name__ == '__main__':
5
# test1.py executed as script
6
# do something
7
some_func()
8
service.py
JavaScript
1
11
11
1
import test1
2
3
def service_func():
4
print 'service func'
5
6
if __name__ == '__main__':
7
# service.py executed as script
8
# do something
9
service_func()
10
test1.some_func()
11