如何用arg将模块加载到python中

2024-05-23 13:44:10 发布

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

我要装货一个AMS.py但在我运行它之前我不知道它在哪里。我想把它作为输入参数,通过argv访问。我用的是:

从AMS导入*

我现在想用只对指定的路径执行相同操作的东西来替换它。你知道吗


Tags: py路径参数amsargv装货
2条回答
from sys import argv

使用上述语句。你知道吗

fileName=argv[0]

您可以使用^{}

这里是test.py

# test.py
import sys

filename = sys.argv[1]
f = __import__(filename[:-3]) # This removes the `.py` extension
f.test()

这里是test2.py

# test2.py
def test():
    print('hello world')

通过命令行运行以下命令:

python test.py test2.py

提供以下输出:

hello world

如果确实要加载本地范围中的所有内容,则必须执行以下操作:

filename = sys.argv[1]
f = __import__(filename[:-3], globals(), locals(), ['*'])
for k in dir(f):
    locals()[k] = getattr(f, k)

test()

相关问题 更多 >