gpt4 book ai didi

python - 如何导入作为命令行参数提供的另一个 python 文件?

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:40 24 4
gpt4 key购买 nike

这就是a.py的样子

import sys


def test_import(another_python_file):
import another_python_file as b
b.run_me()

if __name__ == '__main__':
print sys.argv
test_import(sys.argv[1].strip())

这就是b.py的样子

def run_me():
print 'I am script b'

当我运行时,我得到

$ python a.py b.py
['a.py', 'b.py']
Traceback (most recent call last):
File "a.py", line 10, in <module>
test_import(sys.argv[1].strip())
File "a.py", line 5, in test_import
import another_python_file as b
ImportError: No module named another_python_file

我需要什么?我希望它导入 b.py 并打印 I am script b

我错过了什么?

最佳答案

a.py:

import os
import sys


def test_import(another_python_file):
b = __import__(another_python_file)
b.run_me()

if __name__ == '__main__':
print sys.argv
test_import(sys.argv[1].strip('.py'))

b.py
def run_me():
print 'I am script b'

$ python a.py b.py
['a.py', 'b.py']
I am script b

我能够引用 http://www.diveintopython.net/functional_programming/dynamic_import.html 做到这一点

关于python - 如何导入作为命令行参数提供的另一个 python 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21639870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com