简体   繁体   English

运行时更改python源

[英]Change python source while running

Is it possible to change python source file while running an application and have this changes reflected immediately in the application? 是否可以在运行应用程序时更改python源文件并立即在应用程序中反映这些更改?

Let say I have a foo.py file with a class Foo. 假设我有一个类Foo的foo.py文件。 In other module I'm calling functions on the Foo on user action. 在其他模块中,我在用户操作上调用Foo上的函数。 Now, I would like to change source of the Foo without restarting the application and on next user input see the results of the new code. 现在,我想在不重新启动应用程序的情况下更改Foo的源代码,并在下一个用户输入中查看新代码的结果。

Would that be possible? 这可能吗?

Yes, but it ill advised — code which changes itself (although necessary in some cases) is notoriously hard to debug. 是的,但不明智 - 代码自身发生了变化(虽然在某些情况下是必要的)但是很难调试。 You're looking for the reload method. 你正在寻找reload方法。 The way that you would get it to work would be to modify the source file and then call reload on the module, then repeat. 你可以让它工作的方法是修改源文件,然后在模块上调用reload,然后重复。

You do have the option of re-assigning and modifying the code within the application itself — something which does not risk race conditions and it will also allow for a more consistent and testable environment. 您可以选择在应用程序本身内重新分配和修改代码 - 这不会影响竞争条件,也可以实现更加一致和可测试的环境。 For an example, I would recomment Ignacio Vazquez-Abrams 's answer . 举个例子,我会推荐Ignacio Vazquez-Abrams的回答


Have you tried to see what you could manage by merely changing a state (an external config file, database entry, etc) 您是否曾尝试通过仅更改状态(外部配置文件,数据库条目等)来查看可以管理的内容

The following module can probably change whatever you need, not that it's a good idea to use, other than to muck around : ) 以下模块可能会改变您需要的任何内容,而不是使用它是一个好主意,除了捣乱:)

Note that it will not change your source, which would probably be a disaster, especially if you make a coding error. 请注意,它不会更改您的源,这可能是一个灾难,特别是如果您编码错误。 The 'safer' option would be to play with byteplay “更安全”的选择是使用字节播放

http://wiki.python.org/moin/ByteplayDoc http://wiki.python.org/moin/ByteplayDoc

Ok, now let's play! 好的,现在让我们玩吧! Say we want to change the function, to print its arguments in reverse order. 假设我们要更改函数,以相反的顺序打印其参数。 To do this, we will add a ROT_TWO opcode after the two arguments were loaded to the stack. 为此,我们将在将两个参数加载到堆栈后添加ROT_TWO操作码。 See how simple it is: 看看它有多简单:

>>> from byteplay import *
>>> from pprint import pprint
>>> def f(a, b):
...     print (a, b)
...
>>> f(3, 5)
(3, 5)
>>> c = Code.from_code(f.func_code)
>>> c.code[3:3] = [(ROT_TWO, None)]
>>> f.func_code = c.to_code()
>>> f(3, 5)
(5, 3)
>>> f(3, 5)
(5, 3)

If you are using a defined set of options but want to preserve the same function call, you can also do something like the following 如果您使用一组已定义的选项但希望保留相同的函数调用,则还可以执行以下操作

class Foo(object):
     def fn(self):
         pass
     def op1(self):
         print "HELLO"
     #etc

>>> a = Foo()
>>> a.fn()
>>> a.fn = a.op1
>>> a.fn()
HELLO

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

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