简体   繁体   English

如何在python提示符下从函数打印变量

[英]How to print a variable from a function at python prompt

There are various python files in a directory and all these contain a function desciption() as follows : 目录中有各种python文件,所有这些文件都包含一个函数desciption(),如下所示:

def description():
    desc = 'something'
    return desc

Now I have main.py as follows : 现在我有main.py如下:

def a():
    pth = os.listdir('homedir/workspace')
    for filename in pth :
        exec "import " + filename
        desc = eval(filename + '.desciption()')
    print desc

Right now when I run python main.py, nothing happens. 现在当我运行python main.py时,没有任何反应。 How do I print this desc when I run python main.py? 运行python main.py时如何打印此desc? Thanks in advance! 提前致谢!

Assuming the import worked, and that you have imported a module called filename in each iteration, then you could get the module by name, and call its descrpition() method: 假设导入工作,并且您在每次迭代中导入了一个名为filename的模块,那么您可以按名称获取模块,并调用其descrpition()方法:

import sys
mod = sys.modules[filename]
print mod.description()

But note that it may make more sense to print the module's pydocs: 但请注意,打印模块的pydocs可能更有意义:

print mod.__doc__

You didn't close quotes properly in this line: 您没有在此行中正确关闭引号:

pth = os.listdir('homedir/workspace)

Also you should not use eval here: 你也不应该在这里使用eval:

desc = eval(filename + '.desciption()')

and I assume you wanted to import by variable here: 我假设您想通过变量导入:

        exec "import " + filename

This is how it should look like: 它应该是这样的:

def a():
    import importlib

    pth = os.listdir('homedir/workspace')
    for filename in pth :
        mdl = importlib.import_module(os.path.splitext(filename)[0])
        desc = mdl.description()
        print desc

see https://docs.python.org/2/library/importlib.html#importlib.import_module 请参阅https://docs.python.org/2/library/importlib.html#importlib.import_module

https://docs.python.org/2/library/os.path.html#os.path.splitext https://docs.python.org/2/library/os.path.html#os.path.splitext

  1. You missed the closing ' in the pth variable 你错过了pth变量中的结束'
  2. You've referenced desc on the last line without declaring it first. 你已经在最后一行引用了desc而没有先声明它。
    Start your function with desc = None 使用desc = None启动函数
def a():
    pth = os.listdir('homedir/workspace')

    for filename in pth:
        module_name = os.path.splitext(filename)[0]
        exec "import " + module_name
        desc = eval(module_name + '.description()')
        print desc

make sure the main.py located at the same path with your modules. 确保main.py与您的模块位于同一路径。 or add it to sys path by 或者将其添加到sys路径中

import sys
sys.path.append(r"homedir/workspace")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM