getting started, .py file

Steve Holden steve at holdenweb.com
Mon Feb 20 16:51:58 EST 2006


nibiery at hotmail.com wrote:
> I am just getting started with Python, and I think I may be thinking
> about it wrong. I'd like to be able to work interactively with some
> code that I've got in a file. The only interpreted language I have much
> experience with is Tcl/Tk, and in that I would use "source file.tcl" in
> the console to load my source. Is there a similar command in python? I
> know I can run my file as a script, but since I'm just experimenting
> with how the language works, I want to have more flexibility to be able
> to interactively check the contents of variables and define one piece
> at a time. Am I missing something obvious, or am I not thinking about
> Python properly?
> 
Yes. If your code is in "mycode.py" then start up the interactive 
interpreter and enter

import mycode

at the ">>>" prompt. You will now find that names you have defined in 
the mycode module can be referred to as mycode.this, mycode.that and so 
on, allowing you to interactively play with the features of you module.

A related technique (possibly acceptable for interactive testing but 
definitely *not* recommended for production use) is

from mycode import *

which puts the names directly into the importing module's (that is to 
say the interactive interpreter's) namespace and allows you to refer to 
them directly as this, that, and so on.

This interactive design is one on the Python programmer's secret 
weapons, as it makes it so easy to try things out and be sure you have 
got your Python correct.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list