How to run another .py file w/o exec command?

Christian von Essen christian at mvonessen.de
Sun Mar 28 09:11:46 EST 2004


CaptainN at altel.net wrote:
> Hi everybody,
> 
> I'm sure there's a way to do this, but I can't find it.  How can I execute
> another .py file from my first .py file without using an exec* command?
> They're both in the same directory, and it would be nice to have some
> run("another.py") type statement as opposed to a big exec with absolute
> pathnames and garbage like that.
> 
> It works the way I have it, but it just seems like a bad way in general to
> do it.  I'm runnning Python 2.3.3 on win32.
> 
> Thanks!
> CaptainN
> 
> 
> 
I'm really new to python, but there are several ways with the import 
statement:
1) If the code you want to execute is not in a class but just like this:
File: other.py
class A:
     pass

print "You've called me!"

then you can just import it with "import other" and the print statement 
gets executed, like any other thing at column 0
2) If 1) is not the case i.e.
File: other.py
class A:
     pass

def method():
     print "You've called me!"

you can import it with "import other", too and just do "other.method()" 
or "from other import *" and "method()"

Christian von Essen



More information about the Python-list mailing list