Running a file, with a relative filename

Fredrik Lundh fredrik at pythonware.com
Sun May 16 09:29:52 EDT 1999


Phil Hunt <philh at vision25.demon.co.uk> wrote:
> What's the difference? If I run (from the shell prompt):
> 
>    $ python prog1.py
> 
> Is prog1 a script or a module?

it's a script.

to see the difference, add the following
statements to the start of that file:

print __name__
print __file__

if you run it as above, you'll get:

__main__
Traceback (innermost last):
  File "prog1.py", line 2, in ?
NameError: __file__

> What if I run 
>  
>    $ prog1.py
> 
> and start the file with #!/usr/lib/python ?

still a script:

__main__
Traceback (innermost last):
  File "prog1.py", line 3, in ?
NameError: __file__

on the other hand, if you *import* prog1.py,
you'll get a module named "prog1":

$ python
>>> import prog1
prog1
prog1.py
>>>

(note that if you import prog1 from itself, you'll
get two instances of prog1; one named "__main__",
and one named "prog1".  you probably don't want
to do that...).

</F>





More information about the Python-list mailing list