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

Chris Angelico rosuav at gmail.com
Sun Nov 3 19:42:39 EST 2019


On Mon, Nov 4, 2019 at 11:36 AM <jfong at ms4.hinet.net> wrote:
>
> Peter J. Holzer於 2019年11月4日星期一 UTC+8上午3時59分36秒寫道:
> > 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!"
>
>
> I innocently thought that when import module through "from test import *", I am working on test's globals under REPL. I didn't noticed the REPL has its own globals.
>

Ah, that's a fair point. If you specifically WANT that behaviour, what
you can do is invoke the script interactively:

python3 -i test.py

That'll run the script as normal, and then drop you into the REPL. All
your interactive globals *are* that module's globals.

ChrisA


More information about the Python-list mailing list