[Tutor] How to execute other python program within a python program? [using modules]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 19 Sep 2002 20:23:20 -0700 (PDT)

On Fri, 20 Sep 2002, Hy Python wrote:

> Could you please tell me:
> How to execute other python program within a python program?
> I mean that:
> if have script1.py and script2,
> how can I execute "python script1.py para1 para2" in script2?
> Thanks a lot for your help.

Hi Hy,

Hmmm... My, my.  *grin*  Please forgive me --- I just couldn't resist.

If you want to run the whole other program, you can use the os.system()
function.  Here's an example of how it might work:

import os
print "I will call this other program called hello.py"
os.system("python hello.py")

and if everything works the way we expect, this should get Python to run
the other command.

However, if both programs are Python, there's a way of being able to take
individual pieces of one file, and use them in another.  We can do this by
by first 'importing' a file --- once we do this, then we can call the
functions that are defined in the imported program.

For example, let's say we have two files.  Let's call the first one

### myutils.py
def sqrt(x): return x ** 0.5
def double(x): return x + x

What we'll do, in the second file, is use stuff from the myutils file.
Let's call this file 'main.py':

### main.py
import myutils

print "Hey, this is something from the myutils file:", myutils.sqrt
print "Let's use it!  The square root of forty-two is",
print myutils.sqrt(42)

print "Let's try the other function:",
print myutils.double("double")

This is one way to use parts of one program within another, and we'd
usually call the utility program a "module" because it contains a bunch of
pieces that we can mix and match.

The Useless Python website has a good tutorial on using modules; you can
take a look at it here:


I think I rushed the explanation a bit; I think I drank too much coffee
today.  *grin* Please feel free to ask more questions where things are
fuzzy, and one of us here can help explain it better.

Talk to you later!