[英]Execute python solvers from another python script using flag variables
我目前正在研究一個 python 管道,我需要從 python 代碼中調用不同的求解器/腳本並執行它們。 由於涉及到不同類型的代碼,我想根據標志參數調用這些求解器並相應地運行它們。 下面是我打算做的一個例子:
所以有兩個或更多的python代碼,通常有100行代碼,但這里我舉了一個通用的例子
#script1.py
import numpy
def test1():
print('This is script One')
if __name__ == '__main__':
test1()
#script2.py
import numpy
def test2():
print('This is script two')
if __name__ == '__main__':
test2()
目前我從另一個腳本main.py
執行它們
#main.py
import numpy
from script1 import *
from script2 import *
if __name__=='__main__':
test1()
test2()
這個main.py
執行了我不想要的兩個。 我想使用標志變量並根據需要執行它們。 這可以使用argparse
命令行解析來完成嗎? 因為每個script.py
中可能還有其他標志可以運行。 這也是我更喜歡的。
謝謝
您可以執行以下操作:
#main.py
import numpy
import sys
from script1 import test1
from script2 import test2
if __name__=='__main__':
# sys.argv[0] is the executable so we skip it.
for arg in sys.argv[1:]
if arg == "test1":
test1()
elif arg == "test2":
test2()
現在你可以執行你的測試了
python main.py test1
python main.py test2
# or if you want to repeat a test several times or run multiple tests
# will execute test1, then test2 then test1 again
python main.py test1 test2 test1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.