1.標準輸入
input()、raw_input()
Python 3.x 中 input() 函式可以實作提示輸入,python 2.x 中要使用 raw_input(),例如:
foo = input("Enter: ") # python 2.x 要用 raw_input()
print("You input: [%s]" % (foo))
# 測驗執行
Enter: abc de
You input: [abc de] # 讀取一行(不含換行符)
sys.stdin
使用 sys.stdin 可以獲取標準輸入的檔案句柄物件,例如:
import sys
print("Enter a line: ")
line = sys.stdin.readline() # 讀取一行(包括換行符)
print("Line: [%s]\n%s" % (line, "-"*20))
print("Enter a character: ")
char = sys.stdin.read(1) # 讀取一個位元組
print("Char: [%s]\n%s" % (char, "-"*20))
print("Enter a multi-lines: ")
lines = sys.stdin.read() # 讀取到檔案尾
print("Lines: [%s]" % (lines))
# 測驗執行
Enter a line:
This is a single line <======== 輸入了一行,然后回車
Line: [This is a single line
] <======== 輸出有換行符
--------------------
Enter a character:
abc <======== 輸入了三個位元組
Char: [a] <======== 只讀取了一個位元組
--------------------
Enter a multi-lines:
first line
second line
last line <======== 輸入三行(換行)后,windows 下按 Ctrl+Z,linux 下按 Ctrl + D 結束輸入
Lines: [bc <======== 上一次未讀完的三個位元組(兩個字符 + 一個換行符)
first line
second line
last line
] <======== 最后一行也有換行符
2.標準輸出
print 可以自動換行,例如:
print("%s is %0.2f, %d is a integer" % ("PI", 3.14, 123)) # 格式同 C 語言中的 printf()
print("{0} is {1}, {2} is a integer".format("PI", 3.14, 123))
print("{foo} is {bar}, {qux} is a integer".format(foo="PI", bar=3.14, qux=123))
#Python小白學習交流群:711312441
# 測驗執行
PI is 3.14, 123 is a integer
PI is 3.14, 123 is a integer
PI is 3.14, 123 is a integer
sys.stdout
使用 sys.stdout 可以獲取標準輸出的檔案句柄物件,例如:
import sys
sys.stdout.write("%s is %0.2f, %d is a integer\n" % ("PI", 3.14, 123)) # 格式同 C 語言中的 printf()
sys.stdout.write("{0} is {1}, {2} is a integer\n".format("PI", 3.14, 123))
sys.stdout.write("{foo} is {bar}, {qux} is a integer\n".format(foo="PI", bar=3.14, qux=123))
執行結果與 print 的示例一樣,(注:write()不會自動換行,這里加了換行符)
3.標準錯誤
sys.stdout
使用 sys.stderr 可以獲取標準錯誤的檔案句柄物件,示例略(將 sys.stdout 中示例中的 stdout 替換為 stderr 即可),
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/556688.html
標籤:其他
上一篇:MicroPython物聯網開發入門1歡迎上賊船ESP8266
下一篇:返回列表