从python脚本动态导入变量
如何在递归函数中包含来自文件的变量 到目前为止,我所拥有的:从python脚本动态导入变量,python,import,Python,Import,如何在递归函数中包含来自文件的变量 到目前为止,我所拥有的: #!/usr/bin/python3 import sys def parseFile(pathToFile : str): print(pathToFile) fileVars = __import__(pathToFile, None, None, ['fileList'], 0) for file in fileVars.fileList: parseFile(f
#!/usr/bin/python3
import sys
def parseFile(pathToFile : str):
print(pathToFile)
fileVars = __import__(pathToFile, None, None, ['fileList'], 0)
for file in fileVars.fileList:
parseFile(file)
parseFile(sys.argv[1])
此代码有两个问题:
- include语句执行导入的脚本(我不想更改脚本)
- 它在子文件夹中找不到文件
我知道上面的内容很粗糙。问题是:(如何)我可以通过大量的黑客攻击来完成我想要的,这些攻击总体上会更干净,然后再编写/包括(外部)解析器。您必须在子文件夹中创建一个名为
\uu init\uuuuuuuuuuuy.py
的文件。这可能是空的。在朋友的帮助下,我得到了它:
import ast
def getVarFromPy(pathToFile: str, varName: str):
my_ast = ast.parse(open(pathToFile).read()) # fd will be collected by GC sometime in the future
return next(eval(compile(ast.Expression(obj.value), '<ast>', mode='eval')) for obj in my_ast.body if
isinstance(obj, ast.Assign) and obj.targets[0].id == varName)
导入ast
def getVarFromPy(路径文件:str,varName:str):
my_ast=ast.parse(open(pathToFile.read())#将来某个时候GC将收集fd
如果需要,返回my_ast.body中obj的下一步(eval(compile(ast.Expression(obj.value))“”,mode='eval'))
isinstance(obj,ast.Assign)和obj.targets[0]。id==varName)
出人意料的干净。要不要解释一下投票结果?我做了家庭作业。我在网上找不到更多有用的信息。我是python的初学者。谢谢你的提示,但我希望解决方案包含在主脚本中。(我想投票支持你的评论,但遗憾的是我没有足够的代表。)