如何通过用户的命令行参数选择导入的 python 文件



在主python文件中,我导入另一个python文件,说他们的名称为file1,file2,file3,所有这些都有一个函数,它们的函数名为 scrape()。我正在尝试选择哪个文件的scrape()将根据用户输入运行,如以下内容:

python main.py file1

这是我代码的相关部分:

import file1
import file2
import file3
fileName = sys.argv[1]
for func in ['%s.scrape' % fileName]:
    meta, infos = func()

但是,我收到此错误消息:

Traceback (most recent call last):
File "main.py", line 50, in <module>
meta, infos = func()
TypeError: 'str' object is not callable

请注意,当我使用for func in [file1.scrape]:时它可以使用,我只是无法将用户输入用作导入的文件名。有人可以告诉我怎么做吗?

您试图将func称为函数,当它确实是您从命令行构建的字符串时。

出于您的目的,正如Prashant的链接帖子中所述,您可能需要使用IMP模块之类的东西。

这是一个快速示例

import sys
import imp
# `imp.load_source` requires the full path to the module
# This will load the module provided as `user_selection`
# You can then either `import user_selection`, or use the `mod` to access the package internals directly
mod = imp.load_source("user_selection", "/<mypath>/site-packages/pytz/__init__.py")

# I'm using `user_selection` and `mod` instead of `pytz`
import user_selection
print(user_selection.all_timezones)
print(mod.all_timezones)

在您的情况下,您可能必须使用imp.find_module从名称中获取完整的路径,或者直接在命令行中提供完整路径。

这应该是起点

import sys
import imp
file_name = sys.argv[1]
f, filename, desc = imp.find_module(file_name, ['/path/where/modules/live'])
mod = imp.load_module("selected_module", f, filename, desc)
mod.scrape()

最新更新