如何从位置类似于 "C:\Users\SomeFolder\PythonFile.py" 的 python 脚本中提取所有变量及其值?
How to extract all variable and their value from a python script with location like "C:\\Users\\SomeFolder\\PythonFile.py"?
我正在使用 python 制作的文本编辑器,我想在我的编辑器中添加 Variable Explorer 的功能 我无法从 python 文件中提取变量值。我的基本工作原理是我的程序获取当前编辑文件的位置并尝试导入它,但我无法导入,因为那是字符串而不是对象。这有点令人困惑,所以让我展示一下代码。
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__)
来自
主要问题是无法从字符串导入
import editfile # the problem
因为是字符串,import 不接受字符串
所以我想要一个函数,它可以从任何位置的特定 python 文件中打印所有变量及其值。
使用importlib
import importlib
importlib.import_module(editfile)
还要注意,str
在Python、replace
、returns中是不可变的新字符串,不会修改其参数。
所以你得到:
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))
我正在使用 python 制作的文本编辑器,我想在我的编辑器中添加 Variable Explorer 的功能 我无法从 python 文件中提取变量值。我的基本工作原理是我的程序获取当前编辑文件的位置并尝试导入它,但我无法导入,因为那是字符串而不是对象。这有点令人困惑,所以让我展示一下代码。
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__)
来自
主要问题是无法从字符串导入
import editfile # the problem
因为是字符串,import 不接受字符串
所以我想要一个函数,它可以从任何位置的特定 python 文件中打印所有变量及其值。
使用importlib
import importlib
importlib.import_module(editfile)
还要注意,str
在Python、replace
、returns中是不可变的新字符串,不会修改其参数。
所以你得到:
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))