我想寫一些結果我從一個範圍的函數得到,但我不明白爲什麼文件是空的。該功能工作正常,因爲我可以在打印機中看到控制檯中的結果。首先,我創建了正在工作的文件,因爲它已創建;輸出文件名取自一個字符串,並且該部分也在工作。所以下面會在指定路徑的文件:文件被創建,但不能用Python編寫
report_strategy = open(output_path+strategy.partition("strategy(")[2].partition(",")[0]+".txt", "w")
它創建從一個名爲「戰略」串取名稱的文本文件,例如:
strategy = "strategy(abstraction,Ent_parent)"
一個名爲「抽象.txt「是在輸出路徑文件夾中創建的。到現在爲止還挺好。但我無法寫任何東西到這個文件。我有一個範圍的幾個整數
maps = (175,178,185)
這是功能:
def strategy_count(map_path,map_id)
下面的循環不會在範圍「地圖」每個項目的計數返回一個整數:
report_strategy.close()
:
for i in maps:
report_strategy.write(str(i), ",", str(strategy_count(maps_path,str(i))))
和文件在端封閉
現在以下幾點:
for i in maps:
print str(i), "," , strategy_count(maps_path,str(i))
確實給我什麼,我想在控制檯:
175 , 3
178 , 0
185 , 1
我在想什麼?該功能起作用,文件被創建。我在控制檯中看到輸出,但我無法在文件中寫入相同的內容。當然,我關閉了文件。
這是讀取文本文件(實際上是Prolog文件)的程序的一部分,並運行一個名爲Clingo的應答集編程解決方案。然後讀取輸出以找到發生策略的實例(具有特定規則的一系列操作)。整個代碼:
import pmaps
import strategies
import generalization
# select the strategy to count:
strategy = strategies.abstraction_strategy
import subprocess
def strategy_count(path,name):
p=subprocess.Popen([pmaps.clingo_path,"0",""],
stdout=subprocess.PIPE,stderr=subprocess.STDOUT,stdin=subprocess.PIPE)
#
## write input facts and rules to clingo
with open(path+name+".txt","r") as source:
for line in source:
p.stdin.write(line)
source.close()
# some generalization rules added
p.stdin.write(generalization.parent_of)
p.stdin.write(generalization.chain_parent_of)
# add the strategy
p.stdin.write(strategy)
p.stdin.write("#hide.")
p.stdin.write("#show strategy(_,_).")
#p.stdin.write("#show parent_of(_,_,_).")
# close the input to clingo
p.stdin.close()
lines = []
for line in p.stdout.readlines():
lines.append(line)
counter=0
for line in lines:
if line.startswith('Answer'):
answer = lines[counter+1]
break
if line.startswith('UNSATISFIABLE'):
answer = ''
break
counter+=1
strategies = answer.count('strategy')
return strategies
# select which data set (from the "pmaps" file) to count strategies for:
report_strategy = open(pmaps.hw3_output_path+strategy.partition("strategy(")[2].partition(",")[0]+".txt", "w")
for i in pmaps.pmaps_hw3_fall14:
report_strategy.write(str(i), ",", str(strategy_count(pmaps.path_hw3_fall14,str(i))))
report_strategy.close()
# the following is for testing the code. It is working and there is the right output in the console
#for i in pmaps.pmaps_hw3_fall14:
# print str(i), "," , strategy_count(pmaps.path_hw3_fall14,str(i))
您發佈的代碼看起來很好。請張貼其餘的。 – Kevin 2014-09-29 18:50:04
@Kevin我更新了這篇文章,並把這個文件的所有代碼。它讀取一些其他文件(前三個導入),它們基本上將一些路徑名和Prolog規則存儲在文本中。 – mdinar 2014-09-29 19:11:57