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

How to choose an imported python file by user's command line argument

在主 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 作为函数调用,而实际上它是您从 command-line 参数构建的字符串。

出于您的目的,如 prashant 的链接 post 中所述,您可能需要使用类似 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()