[英]My code neither produces output nor an error, code looks correct, how to troubleshoot with no output?
我正在嘗試解決 Zed Shaw 的“Learn Python the Hard Way”中的 Ex 41。 我已經為它創建了文件。 該練習從作者的網站檢索文本文件。 當我在命令行 (Ubuntu) 上運行它時,它只會讓我回到沒有可見輸出的提示符。
我不確定如何確定問題所在。 我試過了:
仔細檢查代碼。 據我所知,代碼看起來與本書相同。
相反,在 IDLE 中運行它,不產生任何輸出,只是返回到提示
使用 -v 運行 python(它沒有產生任何結果)
將 URL 更改為 https,以及
驗證單詞列表在該 URL 上是否可用(確實如此)。
我的任何其他 python 練習仍然運行良好。 有沒有辦法查看更多輸出(如日志文件,或強制更多輸出的方法),我可以嘗試找出發生了什么?
import random
from urllib import urlopen
import sys
WORD_URL = "https://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class %%%(%%):":
"Make a class named %% that is-a %%.",
"class %%(object):\n\tdef_init_(self, ***)" :
"class %% has-a _init_ that takes self and *** parameters.",
"class %%(object):\n\tdef ***(self, @@@)":
"class %%% has-a function named *** that takes self and @@@ parameters.",
"*** = @@@()":
"Set *** to an instance of class %%%.",
"***.***(@@@)":
"From *** get the *** function, and call it with parameters self, @@@.",
"***.*** = '***'":
"From *** get the *** attribute and set it to '***'."
}
#do they want to drill phrases first
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True
#load up words from the website
for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip())
def convert(snippet, phrase):
class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("%%"))]
other_names = random.sample(WORDS, snippet.count("***"))
results = []
param_names = []
for i in range(0, snippet.count("@@")):
param_count = random.randint(1,3)
param_names.append(', '.join(random.sample(WORDS, param_count)))
for sentence in snippet, phrase:
result = sentence[:]
#fake class class_names
for word in class_names:
result = result.replace("%%%", word, 1)
#fake other names
for word in other_names:
result = result.replace("***", word, 1)
#fake parameter lists
for word in param_names:
result = result.replace("@@@", word, 1)
results.append(results)
return results
# keep going until they hit ctrl-D
try:
while True:
snippets = PHRASES.keys()
random.shuffle(snippets)
for snippet in snippets:
phrase = PHRASES[snippet]
question, answer = convert(snippet, phrase)
if PHRASE_FIRST:
question, answer = answer, question
print question
raw_input("> ")
print "ANSWER: %s\n\n" % answer
except EOFError:
print "\nBye"
正如 jasonharper 所提到的,您的打印內容在convert
內部調用,而根本沒有調用。
如果您正在尋找一種更通用的調試方法來調試未發生的事情(假設您有一些非常大而復雜的腳本),我可以建議您使用以下方法:
print "start"
放在腳本的開頭,並在似乎沒有處理的指令之前print "end"
print "end"
:一次將其移出條件塊或循環,或移至函數定義的第一行或從函數定義移至調用它的位置。 在某些時候,您會看到“結束”輸出出現(在這種情況下,檢查塊的條件或函數內的返回語句其他可能阻止您到達先前print "end"
的位置的事情); 或者,就像在您的示例中一樣,您會注意到該調用根本不在您的程序中print "start"
或除了print "end"
之外可能很有用 - 但想法是相同的:您將它們彼此靠近並尋找“開始顯示,結束不顯示”的時刻情況變化
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.