views:

1402

answers:

6

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.

eg:

test1.py

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

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.

+4  A: 

This is possible using

execfile("test2.py")

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

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

balpha
A: 

Why not just import test1? every python script is a module. Better way would be to have function e.g. main/run in test1.py , import test1 and run test1.main() or you can execute test1.py as a subprocess.

Anurag Uniyal
A: 

You should not be doing this. Instead, do:

test1.py:

 def print_test():
      print "I am a test"
      print "see! I do nothing productive."

service.py

#near the top
from test1 import print_test
#lots of stuff here
print_test()
thedz
+1  A: 

Use import test1 for the 1st use - it will execute the script. For later invocations, treat the script as an imported module, and call the reload(test1) method.

When reload(module) is executed:

  • Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called

A simple check of sys.modules can be used to invoke the appropriate action. To keep referring to the script name as a string ('test1'), use the 'import()' builtin.

import sys
if sys.modules.has_key['test1']:
    reload(sys.modules['test1'])
else:
    __import__('test1')
gimel
+2  A: 

If you want test1.py to remain executable with the same functionality as when it's called inside service.py, then do something like:

test1.py

def main():
    print "I am a test"
    print "see! I do nothing productive."

if __name__ == "__main__":
    main()

service.py

import test1
# lots of stuff here
test1.main() # do whatever is in test1.py
Michael Schneider
+7  A: 

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()
ars