我想提取名为value
的变量,该变量在第二个任意选择的python脚本中设置。如何从另一个脚本内执行python脚本后动态导入变量
该过程在pyhton的交互模式下手动执行时会生效,但是当我从命令行运行主脚本时,不会导入value
。
主脚本的输入参数已成功转发,但value
似乎在执行脚本的本地范围内。
我已经尝试在主脚本中定义value
,并且我还尝试将其可访问性设置为全局。
这是剧本我到目前为止
import sys
import getopt
def main(argv):
try:
(opts, args) = getopt.getopt(argv, "s:o:a:", ["script=", "operations=", "args="])
except getopt.GetoptError as e:
print(e)
sys.exit(2)
# script to be called
script = ""
# arguments that are expected by script
operations = []
argv = []
for (opt, arg) in opts:
if opt in ("-o", "--operations"):
operations = arg.split(',')
print("operations = '%s'" % str(operations))
elif opt in ("-s", "--script"):
script = arg;
print("script = '%s'" % script)
elif opt in ("-a", "--args"):
argv = arg.split(',')
print("arguments = '%s'" % str(argv))
# script should define variable 'value'
exec(open(script).read())
print("Executed '%s'. Value is printed below." % script)
print("Value = '%s'" % value)
if __name__ == "__main__":
main(sys.argv[1:])
在它失败有什么办法?请明确点。错误类型,消息,意外行为,无论如何。 – paidhima
您是否试过'导入'而不是?这通常比'exec'更安全。 – cdarke
@paidhima我编辑了这个问题。我的意思是,这个价值并没有被导入。 – mike