我正在做一个项目,我想运行相同的脚本,但使用两个不同的软件api。
我所拥有的:-每个软件都有一个模块,其中我有相同的类和方法名称。-一个构造脚本,我需要在其中调用这些类和方法。
我不想重复构造代码,而是通过更改导入的模块来运行相同的代码。
示例:
first_software_module.py
import first_software_api
class Box(x,y,z):
init():
first_software_api.makeBox()
second_software_module.py
import second_software_api
class Box(x,y,z):
init():
second_software_api.makeBox()
construction.py
first_box = Box(1,2,3)
我想先用第一个模块运行construction.py,然后用第二个模块运行。我尝试过导入、execfile,但这些解决方案似乎都不起作用。
我想做的事:
import first_software_module
run construction.py
import second_software_module
run construction.py
您可以尝试将命令行参数传递给construction.py
。
construction.py
import sys
if len(sys.argv) != 2:
sys.stderr.write('Usage: python3 construction.py <module>')
exit(1)
if sys.argv[1] == 'first_software_module':
import first_software_module
elif sys.argv[1] == 'second_software_module':
import second_software_module
box = Box(1, 2, 3)
然后可以使用shell脚本中的每个导入类型调用construction.py
,比如main.sh
。
main.sh
#! /bin/bash
python3 construction.py first_software_module
python3 construction.py second_software_module
使用chmod +x main.sh
使shell脚本可执行。将其作为./main.sh
运行。
或者,如果您不想使用shell脚本,并且想在纯Python中使用,您可以执行以下操作:
main.py
import subprocess
subprocess.run(['python3', 'construction.py', 'first_software_module'])
subprocess.run(['python3', 'construction.py', 'second_software_module'])
并像通常使用python3 main.py
一样运行main.py
。
您可以传递一个命令行参数,告诉脚本要导入哪个模块。有很多方法可以做到这一点,但我将用argparse
模块进行演示
import argparse
parser = argparse.ArgumentParser(description='Run the construction')
parser.add_argument('--module', nargs=1, type=str, required=True, help='The module to use for the construction', choices=['module1', 'module2'])
args = parser.parse_args()
现在,args.module
将包含您传递的参数的内容。使用此字符串和if-elif
梯形图(或3.10+中的match-case
语法(导入正确的模块,并将其别名为(比方说(driver
。
if args.module[0] == "module1":
import first_software_api as driver
print("Using first_software_api")
elif args.module[0] == "module2":
import second_software_api as driver
print("Using second_software_api")
然后,在Box
类中使用driver
:
class Box(x,y,z):
def __init__(self):
driver.makeBox()
假设我们在一个名为construct.py
的文件中有这个。运行python3 construct.py --help
给出:
usage: construct.py [-h] --module {module1,module2}
Run the construction
optional arguments:
-h, --help show this help message and exit
--module {module1,module2}
The module to use for the construction
运行python3 construct.py --module module1
给出:
Using first_software_api