【问题标题】:Execute a file within a Python 3.x script and keep variables callable在 Python 3.x 脚本中执行文件并保持变量可调用
【发布时间】:2013-12-21 07:51:52
【问题描述】:

我没有找到在另一个 python.py 文件中保持变量定义/可调用的方法 使用“exec”之后。

这是我使用 pyqt 所做的事情: 我想执行一段更大的代码和 所以我使用“exec”来保持我的“gui程序”与我的“计算程序”分开

...gui. stuff...

if self.checkbox.checkState(): #"checkbox" = label of a checkboy in QTDesigner
        x=14

    exec(open("./calculation_where_x_used.py").read()) 

def onClose(self): # this is a button on my gui. labelled "Close"
    print("bye")
    self.close()

当我在 gui 中选中一个复选框后运行它时。代码做了它应该做的事情,但是“calculation_where_x_used.py”中定义的所有类型的矩阵和变量都不能再通过shell调用......

我该如何解决这个问题? PS:我使用 Spyder as 和 Python 3.3

【问题讨论】:

  • 你试过将 globals() 传递给 exec 吗?
  • 您熟悉import 语句吗?这是在单独的文件中使用代码的更惯用的方式。

标签: python user-interface pyqt qt-designer


【解决方案1】:

嗯... ick?

不要(ab)为此使用 eval;将您的计算代码转换为模块,导入并调用它。让它返回结果值 - 问题解决了。

【讨论】:

  • 我如何通过 globals()?
  • @user2956831:明确!全局变量通常是个坏主意。
  • 如何从 exec() 传递所有变量?
  • 这很奇怪,即使我制作了一个与numpy模块一起使用的矩阵全局,我在运行函数from calculation_where_x_used.py import func后无法从shell调用它
  • 尝试from calculation_where_x_used import func(没有.py),停止使用全局变量,在最坏的情况下尝试calculation_where_x_used.myglobalvar
猜你喜欢
  • 1970-01-01
  • 2011-01-29
  • 2014-10-17
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多