作者yueayase (scrya)
看板Python
標題[心得] Pydev + Eclipse
時間Thu Jan 27 23:25:21 2011
如果要用Eclipse 寫 Python的話, 除了下載Pydev以外,有一個小事要注意,例如:
sum = 0
while True:
a_string = input("Enter your age")
if a_string == "No"
print("exit!\n")
break
num = int(a_string)
sum = sum + num
print("current sum = %d" % sum)
這段程式碼在IDLE和python command line運作得很好,但是(輸入No時)在Eclipse會出現:
Traceback (most recent call last):
.....
in <module>
num = int(a_string)
ValueError: invalid literal for int() with base 10: 'No '
為什麼會這樣呢?可以參考以下連結:
http://pydev.org/faq.html
原因是因為當輸入No時, input解讀成 No\r(可用Eclipse的Debug模式觀察)
所以它認為a_string 不是 "No", 而是"No\r"
如此一來在執行 num = int(a_string) 就會出錯,因為根本不能翻譯成integer
但是如果改成if a_string == "No\r",
在IDLE就不正常了,因為它認為input讀到的是"No"
所以要改成:
a_string = input("Enter your age").replace('\r','')
來把'\r'拿掉,
另外在Python 3.0後的版本,好像只有input(), 沒有raw_input(),
兩者似乎和在一起,變成只有input()了
不過Eclipse算是蠻好用的
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.173.157.116
→ qrtt1:為什麼是 \r 你用 mac !? 01/27 23:51
→ StubbornLin:用 str.strip()就可以濾掉 01/27 23:54
→ yueayase:可是我是用windows 01/28 00:29
→ yueayase:不知道為什麼....,但用.replace('\r','')在IDLE和eclipse 01/28 00:30
→ yueayase:都正常 01/28 00:30
推 cobrasgo:這個檔案是在什麼狀況下建立的? 01/28 00:34
→ uranusjr:會不會是因為 Windows 換行是 CRLF, 而 Eclipse 的終端只 01/28 01:25
→ uranusjr:弄掉 LF 所以殘留 CR...? 我都是用 Eclipse 寫完後切去系 01/28 01:26
→ uranusjr:統終端執行所以沒注意過這個問題就是了 01/28 01:26
→ yueayase:直接用Eclipse的run,在console下輸入資料 01/28 03:24
→ yueayase:但我沒設定一些external tool的東西,所以console不會像 01/28 03:26
→ yueayase:shell一樣 01/28 03:26
→ StubbornLin:Eclipse可以設定EOL的格式 你可能選到Mac格式 01/28 13:26