如何从python脚本中提取所有变量及其值,其位置如;C:\\Users\\SomeFolder\\PythonFile.py";?
我正在使用python制作一个文本编辑器,我想在编辑器中添加变量资源管理器的功能,但我无法从python文件中提取变量值。我的基本工作原理是,我的程序获取当前编辑文件的位置并尝试导入它,但我无法导入,因为该字符串不是对象。这是有点混乱,所以让我显示代码如何从python脚本中提取所有变量及其值,其位置如;C:\\Users\\SomeFolder\\PythonFile.py";?,python,python-3.x,python-import,Python,Python 3.x,Python Import,我正在使用python制作一个文本编辑器,我想在编辑器中添加变量资源管理器的功能,但我无法从python文件中提取变量值。我的基本工作原理是,我的程序获取当前编辑文件的位置并尝试导入它,但我无法导入,因为该字符串不是对象。这是有点混乱,所以让我显示代码 fileName='C:\Users\Project.py' class varExplorer: def ShowVarList(editfile): editfile.replace('\','.') ed
fileName='C:\Users\Project.py'
class varExplorer:
def ShowVarList(editfile):
editfile.replace('\','.')
editfile.replace('.py','')
editfile.replace(':','')
# so the file path will be like C.Users.Project
import editfile # the problem
print(editfile.__dict__)# here i will get dictionary of values
varExplorer.ShowVarList(fileName)
为dict获取帮助
print(editfile.__dict__)
从
主要问题是它无法从字符串导入
因为它是一个字符串,导入不接受字符串
因此,我需要一个函数,它可以从任何位置打印特定python文件中的所有变量及其值。使用
importlib
import importlib
importlib.import_module(editfile)
还要注意,str
在Python中是不可变的,replace
返回一个新字符串,并且不修改其参数。
所以你得到:
import importlib
class VarExplorer:
def show_var_list(editfile):
editfile = editfile.replace('\\','.')
editfile = editfile.replace('.py','')
editfile = editfile.replace(':','')
# so the file path will be like C.Users.Project
module = importlib.import_module(editfile) # the solution
print(vars(module))
这将做什么请编辑它并添加一个解释。好的,那么我将如何使用它。uuuu dict_uuuuu提取变量
对象。uuu dict_uuu
和变量(对象)
是等价的,后者更像python,因为它避免使用特殊的隐藏变量。它显示错误ModuleNotFoundError:没有名为'D:\\Sync\\HelpUtilities\\compileman'的模块,因此editfileimportlib.import\u模块(editfile)中的editfile
是“D:\\Sync\\HelpUtilities\\compileman”,它显然不是包名。您是否用editfile=editfile.replace…
更正了代码?似乎尚未进行替换。编辑器不应导入正在编辑的文件。我建议使用ast或类似的方法。
import importlib
class VarExplorer:
def show_var_list(editfile):
editfile = editfile.replace('\\','.')
editfile = editfile.replace('.py','')
editfile = editfile.replace(':','')
# so the file path will be like C.Users.Project
module = importlib.import_module(editfile) # the solution
print(vars(module))