How to call a script from another script?


I have a script named 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 from the script running as a service.

For example:


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


# Lots of stuff here # do whatever is in
Asked By: Josh Smeaton



This is possible in Python 2 using


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

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


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

Answered By: balpha

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

Answered By: Anurag Uniyal

You should not be doing this. Instead, do:

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

#near the top
from test1 import print_test
#lots of stuff here
Answered By: thedz

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']:
Answered By: gimel

If you want to remain executable with the same functionality as when it’s called inside, then do something like:

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

if __name__ == "__main__":

import test1
# lots of stuff here
test1.main() # do whatever is in
Answered By: Michael Schneider

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

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

if __name__ == '__main__':
    # executed as script
    # do something

import test1

def service_func():
    print 'service func'

if __name__ == '__main__':
    # executed as script
    # do something
Answered By: ars

Another way:


print ""


import subprocess"", shell=True)

The advantage to this method is that you don’t have to edit an existing Python script to put all its code into a subroutine.

Documentation: Python 2, Python 3

Answered By: Dick Goodwin
import os

os.system("python arg1 arg2 arg3")  

Using os you can make calls directly to your terminal. If you want to be even more specific you can concatenate your input string with local variables, ie.

command = 'python ' + sys.argv[1] + ' ' + sys.argv[2]
Answered By: Alex Mapley

This is an example with subprocess library:

import subprocess

python_version = '3'
path_to_run = './'
py_name = ''

# args = [f"python{python_version}", f"{path_to_run}{py_name}"]  # works in python3
args = ["python{}".format(python_version), "{}{}".format(path_to_run, py_name)]

res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()

if not error_:
Answered By: Benyamin Jafari

I prefer runpy:

#!/usr/bin/env python
# coding: utf-8

import runpy


Answered By: Flavio

As it’s already mentioned, runpy is a nice way to run other scripts or modules from current script.

By the way, it’s quite common for a tracer or debugger to do this, and under such circumstances methods like importing the file directly or running the file in a subprocess usually do not work.

It also needs attention to use exec to run the code. You have to provide proper run_globals to avoid import error or some other issues. Refer to runpy._run_code for details.

Answered By: Chao Chen

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

Suppose you want to execute a script named ‘’ inside an ‘if’ condition, then use,

if condition:
       import recommend

The technique is different, but works!

Answered By: Ashwin Balani

Add this to your python script.

import os
os.system("exec /path/to/another/script")

This executes that command as if it were typed into the shell.

An example to do it using subprocess.

from subprocess import run

import sys

run([sys.executable, ''])

Answered By: Maisum Abbas

According to the given example, this is the best way:


def foo():
from test1 import foo # might be different if in different folder.

But according to the title, using os.startfile("path") is the best way as its small and it works. This would execute the file specified. My python version is 3.x +.

Answered By: Faraaz Kurawle

I found runpy standard library most convenient. Why? You have to consider case when error raised in script, and with runpy you are able to handle this in code. Both traceback text (to write error in log file for future investigation) and error object (to handle error depends on its type): when with subprocess library I wasn’t able to promote error object from to, only traceback output.
Also, comparing to "import as a module" solution, runpy is better cause you have no need to wrap code of into def main(): function.

Piece of code as example, with traceback module to catch last error text:

import traceback
import runpy #

from datetime import datetime

except Exception as e:
    print("Error occurred during execution at " + str( + " {}".format(
Answered By: Yaroslav Wally
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.