作爲編程的新手,我試圖單獨測試每個函數,確保它的工作正確。 這是我的問題:單純的測試,它的工作原理;將它轉換爲函數並將它們合併成一個腳本,它們不起作用。
例如:純Python腳本和函數之間的技巧?
def getRigs (fileObj):
fileObj.seek(0)
rigList = []
Tag = False
for line in fileObj:
if line.find("[BeginRigs]") != -1:
Tag = True
elif line.find("[EndRigs]") != -1:
Tag = False
elif Tag:
rigList.append(line.strip())
return (rigList)
def getObjects (fileObj):
fileObj.seek(0)
objList = []
Tag = False
for line in fileObj:
if line.find("[BeginObjects]") != -1:
Tag = True
elif line.find("[EndObjects]") != -1:
Tag = False
elif Tag:
objList.append(line.strip())
return (objList)
def dummyRig (rigObj, objName):
dummy = ""
for rig in rigObj:
with open(rig, "r") as infile:
#rigObj.seek(0)
Tag = None
for line in infile:
for obj in objName:
if line.find("ObjectAlias " + obj + "\n") !=-1:
Tag = "Mark"
dummy += line
break
elif line.find("BeginKeyframe") != -1:
if Tag == "Mark":
Tag = "Copy"
break
elif line.find("EndKeyframe") != -1:
if Tag == "Copy":
Tag = None
dummy += line
break
if Tag == "Copy":
dummy += line
return (dummy)
def getBlock (rigObj, objName):
Tag = False
block = ""
for line in rigObj:
if line.find("ObjectAlias " + str(objName) + "\n") != -1:
for line in rigObj:
if line.find("BeginKeyframe") != -1:
Tag = True
elif line.lstrip().startswith("0.000 ") and line.rstrip().endswith("default"):
Tag = False
break
elif Tag:
block += line
return (block)
inputconfig = open("config.cfg", "r")
infile = sys.argv[1]
inputscene = open(infile, "r")
outfile = infile.split(".")[0] + "_updated.fxs"
outputscene = open(outfile, "w")
a_rigList = getRigs (inputconfig)
a_objList = getObjects (inputconfig)
a_dummyRig = dummyRig (a_rigList, a_objList)
#print a_dummyRig #----> Output as expected
tmp = getBlock (a_dummyRig, a_objList)
outputscene.write(tmp) #----> Gvie me empty output!
如果我單獨測試 「getBlock」 功能,它工作正常:
with open("result_from_a_dummyRig", "r") as rigObj, open("result", "w") as output:
Tag = False
for line in rigObj:
if line.find("ObjectAlias " + "rooster_bn_featherLa_rt_08" + "\n") != -1:
for line in rigObj:
if line.find("BeginKeyframe") != -1:
Tag = True
elif line.lstrip().startswith("0.000 ") and line.rstrip().endswith("default"):
Tag = False
break
elif Tag:
output.write(line)
我在做什麼錯?
編輯:添加更多的我的代碼,希望它有助於這個問題。該代碼是設計用於從其他文件複製一些外部數據來更新我當前的文件。
謝謝bruno,我明白了你的觀點。 dummyRig函數給了我一個字符串,但不是「真正的」文件。而getBlock函數需要一個「真實」的文件輸入。對?
仍然希望有人給我更多有用的幫助,我不是程序員,我對python瞭解不多。
你能否提供樣本輸入和預期的輸出以及堆棧跟蹤? –
文件對象是一個迭代器,在第一個for循環之後它將是空的。使用其[[seek(0)'](https://docs.python.org/2/library/stdtypes.html#file.seek)方法將文件指針移回到開頭。 –
你在哪裏定義了'a_objList'?爲什麼當它看起來期待一個對象時,爲什麼用一個字符串(返回'dummyRig()')調用'get_block()'? – Aemyl