【问题标题】:Import variable from external file python从外部文件python导入变量
【发布时间】:2020-12-22 18:08:00
【问题描述】:

我使用 js2py 库翻译了一些 JS 文件。我需要从新创建的 python 文件中获取一个在每个文件中具有相同名称的变量。

with os.scandir(path=r'path_to_folder') as folder:
       for file in folder:
            if file.name.endswith('.js'):
                new_name = os.path.basename(file) + ".py"
                path = os.path.basename(file)
                js2py.translate_file(path, new_name)
                print("Translated")
                print()

它可以将每个 JS 文件转换为 python,但我需要这些变量并且从 new_name('from new_name import var') 导入不起作用。还有其他获取这些变量的方法吗?

【问题讨论】:

  • from new_name import * 工作吗?
  • 我一开始是这样尝试的,但是 python 不能识别 new_name。现在我尝试在一个python文件中翻译js文件并动态导入变量,但它只适用于第一个js文件。

标签: javascript python file


【解决方案1】:

我在Js2Py GitHub 上找到了这个。

>>> print(js2py.translate_js('var $ = 5'))
from js2py.pyjs import *
# setting scope
var = Scope( JS_BUILTINS )
set_global_object(var)

# Code follows:
var.registers(['$'])
var.put('$', Js(5.0))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2018-04-19
    • 2017-05-31
    • 1970-01-01
    相关资源
    最近更新 更多