如何从位置类似于“C:\\Users\\SomeFolder”的python脚本中提取所有变量及其值\\PythonFile.py文件"?

2024-10-03 23:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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__)

I want to extract all the variable names with a python script, from a python file, without editing the python file

主要问题是它无法从字符串导入

import editfile # the problem

因为它是一个字符串,而import不接受字符串

所以我需要一个函数,它可以从任何位置打印特定python文件中的所有变量及其值。你知道吗


Tags: 文件the字符串pyimportprojectfilenamewill
1条回答
网友
1楼 · 发布于 2024-10-03 23:21:47

使用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))

相关问题 更多 >