python - 如何在从另一个脚本中执行 python 脚本后动态导入变量

标签 python file variables python-3.x import

我想提取一个名为 value 的变量,该变量在第二个任意选择的 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:])

最佳答案

value 变量已被 exec 放入本地字典中,但对编译器不可见。您可以像这样检索它:

print("Value = '%s'" % locals()['value'])

我更喜欢导入解决方案

关于python - 如何在从另一个脚本中执行 python 脚本后动态导入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29826430/

相关文章:

由于在环境中设置 NUMBA_DISABLE_CUDA=1,python-CUDA 被禁用

java - 从 mac 发送文件到打印机 - java

python - 你如何在Python中调用存储在变量中的函数,mh

Javascript:匹配变量名称并应用于匹配的变量

linux - 如何在 shell 脚本中回显动态变量的内容

python - 如何使用 OpenCV 从多个摄像头捕获实时视频?

python - 使用 PySide 和 PyKDE4 移动窗口

python - 如何从 URL 中通过其 ID 获取单个资源?

javascript - 本地目录查看器和从 Intranet 浏览器拖放

python - 将 .htm 或 .html 扩展名与 python RE 匹配