Kha*_*tri 5 python subprocess python-2.7
我有一个帮助脚本,我想从主脚本调用它作为服务器.这个主要脚本如下所示:
Class Stuff():
def __init__(self, f):
self.f = f
self.log = {}
def execute(self, filename):
execfile(filename)
if __name__ == '__main__':
#start this script as server
clazz = Stuff()
#here helper_script name will be provided by client at runtime
clazz.execute(helper_script)
Run Code Online (Sandbox Code Playgroud)
现在,客户端将通过向主脚本(服务器)提供其名称来调用此帮助程序脚本.执行后我想在主脚本中保留辅助脚本的变量(即:a,b).我知道一种方法是将这些变量从辅助脚本返回到主脚本.但是有没有其他方法可以保留助手脚本的所有变量.这是帮助脚本的样子:
import os
a = 3
b = 4
Run Code Online (Sandbox Code Playgroud)
我尝试使用execfile和subprocess.
您可以将本地字典传递给execfile
.执行文件后,该字典将包含它定义的局部变量.
class Stuff():
def __init__(self):
self.log = {}
def execute(self, filename):
client_locals = {}
execfile(filename, globals(), client_locals)
return client_locals
if __name__ == '__main__':
#start this script as server
clazz = Stuff()
#here helper_script name will be provided by client at runtime
client_locals = clazz.execute('client.py')
print client_locals
Run Code Online (Sandbox Code Playgroud)
有了你client.py
,这将打印:
{'a': 3, 'b': 4, 'os': <module 'os' from '/Users/.../.pyenv/versions/2.7.6/lib/python2.7/os.pyc'>}
Run Code Online (Sandbox Code Playgroud)
警告execfile
:不要将其与来自不受信任来源的文件一起使用.
归档时间: |
|
查看次数: |
177 次 |
最近记录: |