我有一個script_A,它使用argparser來處理不同的輸入,我使用它來執行一個函數。我現在需要腳本B來調用腳本A,並從內部運行所有腳本A(它處理不同的輸入)。我正在使用Windows。Python:運行腳本處理腳本內的argparser B
目標: Script_B將根據script_A的輸出做進一步的分析。 Script_A的行爲根據傳遞的參數選項而改變。 Script_B的行爲總是相同的。我寧願不將script_A和script_B合併爲一個大型腳本。
目標更新:爲了script_B很好地工作,我需要運行script_A然後通過字典,字典d之一,即計算(從A輸出)被傳遞到B的字典僅在script_A全部運行之前計算。
這是Script_A看起來像
import sys
import os
from argparse import ArgumentParser
def function 1:
#it does stuff....
def function 2:
#it does other stuf...
if __name__ == "__main__":
parser = ArgumentParser(description = "functionA.py -i [--print]
parser.add_argument('-i', '--id', help="Please write A or B", required=True)
parser.add_argument('-r', '--re', help="Please write C or D, required=True)
sysargs = parser.parse_args()
#Variable definitions
if str(sysargs.id) == "A":
#Uses file A located in directory X to perform analysis
#calls function A to perform analysis
elif str(sysargs.id) == "B":
#Uses file B located in Directory Y to perform analysis
#calls function B to perform analysis
if str(sysargs.re) == "C"
#Provides thorough printout of analysis (more in depth for debugging)
if str(sysargs.re) == "D"
#Does Nothing (no debugging option)
一個腳本運行正常,當我使用它它的工作。我使用命令行參數來提交輸入,必需的,有時是可選的。
這是腳本B,我已經試過如下:
import sys
import numpy as np
import os
import script_A
os.system("script_A.py", -i "A" -r "C")
#Other stuff that script B does
import sys
import os
import script_A
exec(script_A.py[-i "A" -r "C"])
#Other stuff that script B does
import os
import sys
from subprocess import call
subprocess.call("script_A.py", -i "A" -r "C")
#Other stuff that script B does
我在這裏看了:Calling an external command in Python
這裏:importing a python script from another script and running it with arguments
,但一直無法從他們在說什麼弄明白。任何幫助是極大的讚賞。我仍然是Python的初學者。
我曾嘗試以下基於評論:
import subprocess
import script_A
p.subprocess.Popen("script_A.py", "-i", "A", "-r", "none", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(stdoutput, erroutput) = p.communicate()
類型錯誤:__init_()得到了關鍵字參數 '標準輸出'
我嘗試添加多個值自我論證,但我得到以下錯誤
p.subprocess.Popen("script_A.py", "-i", "A", "-r", "C", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
類型錯誤:__init_()得到了關鍵字參數 'stderr的' 多個值
import subprocess
import script_A
process= Popen(["script_A", "-i", "A", "-r", "C"], stdout = subprocess.PIPE, stderr=subprocess.STDOUT)
output = process.communicate()
OSERROR:[ERRno2]沒有這樣的文件或目錄
在錯誤目錄執行子中的/subprocess.py
raise ch ild_exception
我不知道這是什麼意思。
爲什麼你需要通過命令行來傳遞參數?只需'輸入'並直接調用函數*。 – jonrsharpe
對不起,您能詳細解釋一下嗎?只是爲了澄清我不需要在腳本B中運行腳本A中的單獨函數。我需要運行整個事情。我還希望能夠靈活地分析參數,以便在我想顯示更多輸出時與不輸出時相比。 –
那麼這些替代方法做了什麼(或不做)?你期望發生什麼?如果你不直接使用它的函數(如'os.system'版本),則不需要'import script_A'。 – hpaulj