简体   繁体   English

在python模块中访问全局变量

[英]Access global variables in a python module

How do I access all global variables inside a module (I don't who they are in advance)? 如何访问一个模块内所有的全局变量(我没有他们事先谁)?

For example 例如

file m.py: 文件m.py:

def a(s):
    exec('print '+s)

main code: 主要代码:

import m
x=2
m.a('x*2')

You want to use eval() here and not exec(). 您要在此处使用eval()而不是exec()。

But what are you actually trying to do....the usage of eval() and exec() is in general bad style and in general not needed (especially scary when it comes to security considerations). 但什么是你真正想要做....的eval()和exec()的用法是在一般的不良作风和一般(当涉及到安全方面的考虑尤其可怕),没有必要的。

You can hack it by directly importing the special __main__ module. 您可以通过直接导入特殊的__main__模块来破解它。 In m.py : m.py

def print_global(name):
  import __main__
  print getattr(__main__, name)

And in the main module: 在主模块中:

import m
x = 2
m.print_global('x')  # prints 2

While this example illustrates how to programatically work with the namespace, this is the kind of thing that should be done sparingly if at all. 尽管此示例说明了如何以编程方式使用名称空间,但这是应该少量执行的操作。

Why can't you just use (okay, if you seriously do have strings somehow, but then since it's almost all in code anyway, it just looks like you've got strings around it for some reason) 您为什么不能只使用(好吧,如果您确实以某种方式确实拥有字符串,但是由于无论如何它几乎都在代码中,因此由于某种原因看起来好像周围都有字符串)

(re-written code): (重写代码):

file m.py: 文件m.py:

def a(s):
    print s

main code: 主要代码:

import m
x=2
m.a(x * 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM