【问题标题】:How to choose an imported python file by user's command line argument如何通过用户的命令行参数选择导入的 python 文件
【发布时间】:2019-11-15 18:49:09
【问题描述】:

在一个主要的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]: 时它可以工作,我只是不能使用用户输入作为导入的文件名。谁能告诉我怎么做?

【问题讨论】:

标签: python python-3.x command-line-arguments argv


【解决方案1】:

你正试图将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()

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2018-02-22
    相关资源
    最近更新 更多