git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

What's the difference between running a script under command box and interpreter?


On 2019-11-01 04:24:38 -0700, jfong at ms4.hinet.net wrote:
> > The globals are your current module's namespace, and functions defines 
> > in a module are bound to that module's namespace.
> > 
> > Strip your test.py back. A lot. Try this:
> > 
> >     def main():
> >       print(rule)
> > 
> > Now, let's use that:
> > 
> >     Python 3.7.4 (default, Sep 28 2019, 13:34:38)
> >     [Clang 8.0.0 (clang-800.0.42.1)] on darwin
> >     Type "help", "copyright", "credits" or "license" for more information.
> >     >>> import test
> >     >>> test.main()
> >     Traceback (most recent call last):
> >       File "<stdin>", line 1, in <module>
> >       File "/Users/cameron/tmp/d1/test.py", line 2, in main
> >         print(rule)
> >     NameError: name 'rule' is not defined

[Explanation snipped]

> I didn't noticed that the interpreter has its own globals. Thanks for reminding.

It's not really "the interpreter" (I think you mean the REPL) which has
it's own globals. Every module/file has its own globals.

The same thing happens non-interactively:

% cat test.py 
def main():
    print(rule)

% cat foo.py 
#!/usr/bin/python3

from test import *

rule = 42
main()

% ./foo.py 
Traceback (most recent call last):
  File "./foo.py", line 6, in <module>
    main()
  File "/home/hjp/tmp/test.py", line 2, in main
    print(rule)
NameError: name 'rule' is not defined

The "rule" identifier in main() refers to a "rule" variable in the
module test. If you set a variable "rule" somewhere else (in foo.py or
the REPL, ...), that has no effect. How should python know that you want
to set the rule variable in the test module?

	hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20191103/6c9159d9/attachment.sig>