[英]How do I make a variable accessible from another python script when accessed from modulename.main() method
I have a simple python script which invokes the main function of another python script. 我有一个简单的python脚本,它调用了另一个python脚本的主要功能。 Something like this:
像这样:
invoker_code.py
: invoker_code.py
:
import os
invoked_code = '/tmp/invoked_code.py'
import sys
if os.path.exists(invoked_code):
sys.append(invoked_code)
else:
sys.exit(1)
import invoked_code
__data_bag = { 'var' : 'value' }
invoked_code.main()
/tmp/invoked_code.py
: /tmp/invoked_code.py
:
def main():
print '%s' %(__data_bag['var'])
I want the invoked_code
to be able to access the variable __dict_bag
from within its code base. 我希望
invoked_code
能够从其代码库中访问变量__dict_bag
。 This should be achieved with minimal or zero code changes on the invoked_code.py
script as this is a third party script and I do not have write access to this script. 这应该通过对
invoked_code.py
脚本进行最少或零个代码更改来实现,因为这是第三方脚本,并且我对该脚本没有写权限。 How can I do that? 我怎样才能做到这一点?
Modules can access and modify each other's global variables: 模块可以访问和修改彼此的全局变量:
module1.py : module1.py :
foobar = [1, 2, 3]
def main():
print foobar[0]
def printx():
print x
module2.py : module2.py :
import module1
print module1.foobar
module1.main()
module1.foobar[0] = 100
module1.main()
module1.x = "exex"
module1.printx()
Running module2.py
: 运行
module2.py
:
[1, 2, 3]
1
100
exex
Note that you can both modify a global variable in the other module, and also create one. 请注意,您可以在另一个模块中修改全局变量,也可以创建一个。 However, I would instead recommend doing as poke said and passing the variable into the invoked function.
但是,我反而建议按戳所述做,并将变量传递给调用的函数。
The main
function in invoked_code
will look up the __data_bag
name within its own scope. invoked_code
的main
函数将在其自己的范围内查找__data_bag
名称。 So it will first try to find it inside of the function itself and then go up to module level, ie what's defined in the invoked_code.py
. 因此,它将首先尝试在函数本身内部找到它,然后进入模块级别,即在
invoked_code.py
定义的invoked_code.py
。
As __data_bag
does not exist in either places, the function won't be able to find it. 由于
__data_bag
都不存在,因此该函数将无法找到它。 So to solve this without changing the invoked_code
, you need to supply the data to a place where the function will look at. 因此,要解决此问题而不更改
invoked_code
,您需要将数据提供给函数将要查看的地方。 The only place you have access to is the module though, so that's the only thing you can do: 但是,您唯一可以访问的地方是模块,所以这是您唯一可以做的事情:
import invoked_code
invoked_code.__data_bag = { 'var' : 'value' }
invoked_code.main()
Note that this is really not a good way to solve this problem though. 注意,这实际上不是解决此问题的好方法。 The proper way to solve this would be to have the
main
function accept a parameter for this: 解决此问题的正确方法是让
main
函数为此接受一个参数:
def main(data_bag):
print '%s' %(data_bag['var'])
Then you could simply pass the value in your invoking script: 然后,您可以简单地在调用脚本中传递值:
invoked_code.main(__data_bag)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.