Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python模块的上下文中执行REPL代码,而不是在main中执行?_Python_Read Eval Print Loop - Fatal编程技术网

在Python模块的上下文中执行REPL代码,而不是在main中执行?

在Python模块的上下文中执行REPL代码,而不是在main中执行?,python,read-eval-print-loop,Python,Read Eval Print Loop,我有一个Python实例,其中有一个REPL open和几个导入的模块。我可以像运行这些模块一样运行代码吗 示例:my.module包含如下代码 some_module_var = 123 def my_function(): return 7 我想能打字 new_module_var = my_function(some_module_var) 以某种形式输入REPL,并将其作为模块的一部分执行,而不是 my.module.new_module_var = my.modu

我有一个Python实例,其中有一个REPL open和几个导入的模块。我可以像运行这些模块一样运行代码吗

示例:my.module包含如下代码

  some_module_var = 123

  def my_function():
    return 7
我想能打字

new_module_var = my_function(some_module_var)
以某种形式输入REPL,并将其作为模块的一部分执行,而不是

my.module.new_module_var = my.module.my_function(my.module.some_module_var)
有什么好的解决办法吗

我已经试过的一件事是

exec(compile("my_function(some_module_var)", "<fake_file>", "exec"),
     my.module, {})
exec(编译(“我的函数(某些模块变量)”,“”,“exec”),
my.module,{})
使用模块作为全局名称空间,但显然名称空间不能是模块

另外,作为一种解决方法,我们可以将每个符号从模块复制到全局名称空间,运行eval,然后复制回更改。。。不过,它并不像Common Lisp的“只需切换REPL包”解决方案那样优雅

或者有一个定制的REPL可以做到这一点


(…我的目标是能够将整个函数发送到正在运行的Python实例,并让它们显示在正确的模块中,而不是显示在
\uuuuu main\uuuuu
中)

事实证明,
exec()
可以做到这一点。您传入的不是模块,而是字典:

d = my.module.__dict__
exec("some_module_var = 42", d, d)
exec("print(some_module_var)", d, d)
事实上,这大致就是Python解释器在
pythonrun.c
中(参见
run\u mod()
PyRun\u InteractiveOneObjectEx()
)所做的事情(从3.6开始),其中内置了
\uu main\uu
作为模块名