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 evaluating it. I'm assuming there's a better way of doing this. Or at least I hope so.

Answer: 
Use [`import test1`](http://docs.python.org/reference/simple_stmts.html#the-import-statement) for the 1st use - it will execute the script. For later invocations, treat the script as an imported module, and call the [`reload(test1)`](http://docs.python.org/library/functions.html#reload) 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`](http://docs.python.org/library/sys.html#sys.modules) can be used to invoke the appropriate action. To keep referring to the script name as a string (`'test1'`), use the ['**import**()'](http://docs.python.org/library/functions.html#__import__) builtin.

```
import sys
if sys.modules.has_key['test1']:
    reload(sys.modules['test1'])
else:
    __import__('test1')

```
This process is somewhat un-orthodox, but would work across all python versions,

Suppose you want to execute a script named 'recommend.py' inside an 'if' condition, then use,

```
if condition:
       import recommend

```

The technique is different, but works!