第1章:Python基礎(chǔ):標(biāo)準(zhǔn)輸入和輸出

點(diǎn)擊上方“ Python學(xué)習(xí)開發(fā) ”,選擇“ 加為星標(biāo) ”
第一時間關(guān)注Python技術(shù)干貨!
Python 3 是一種動態(tài)、解釋型的高級編程語言,以其簡潔明了的語法和強(qiáng)大的功能而廣受歡迎。上一節(jié)介紹 Python 3 中的變量和表達(dá)式,以及它們在 CPython 實(shí)現(xiàn)中的工作方式。本文將介紹Python 3最新版中的標(biāo)準(zhǔn)輸入輸出(I操作,并深入探討這些操作在CPython實(shí)現(xiàn)中的代碼細(xì)節(jié)。
基本輸入輸出操作
1. 打印輸出
在Python中,print()函數(shù)是最常用的輸出方法。它允許你將信息打印到控制臺。例如:
print("Hello, World!")
此外,print()函數(shù)還支持格式化輸出,可以使用str.format()方法或者f-string(Python 3.6+):
name = "cxa"
print("Hello, {}!".format(name))
# 或者使用f-string
print(f"Hello, {name}!")
2. 輸入操作
輸入操作通常通過input()函數(shù)實(shí)現(xiàn),它會暫停程序執(zhí)行,等待用戶輸入。例如:
user_input = input("Please enter your name: ")
print(f"Hello, {user_input}!")
3.第三方打印模塊rich
rich是一個Python庫,它提供了一種在命令行中創(chuàng)建豐富、多彩的文本輸出的方式。rich的目標(biāo)是使命令行輸出更加生動和信息豐富,同時保持代碼的簡潔性和易讀性。它支持多種輸出格式,包括文本、Markdown、JSON等,并且可以很容易地與Python的標(biāo)準(zhǔn)print()函數(shù)結(jié)合使用。
基本使用
from rich import print
print("[bold[red]Hello, World![/red][/bold]")
這將輸出"Hello, World!",其中"Hello, World!"將以紅色粗體顯示。
支持的樣式
rich支持多種文本樣式,包括加粗、斜體、下劃線、高亮等:
from rich import print
# 粗體
print("[bold]This is bold text[/bold]")
# 斜體
print("[italic]This is italic text[/italic]")
# 下劃線
print("[underline]This is underlined text[/underline]")
# 高亮
print("[highlight]This is highlighted text[/highlight]")
顏色輸出
rich還支持多種顏色的文本輸出:
from rich import print
# 多種顏色的輸出
print("[red]This is red[/red] [green]and this is green[/green]")
表格輸出
rich可以很容易地創(chuàng)建表格輸出:
from rich import print
from rich.table import Table
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Column 1", style="cyan")
table.add_column("Column 2", style="yellow")
table.add_column("Column 3", style="green")
table.add_row("Item 1", "Item 2", "Item 3")
table.add_row("Item 4", "Item 5", "Item 6")
print(table)
進(jìn)度條
rich還提供了進(jìn)度條功能,可以用于顯示長時間運(yùn)行的任務(wù)的進(jìn)度:
from rich import print
from rich.progress import track
for i in track(range(100), description="Processing"):
# 模擬任務(wù)
time.sleep(0.1)
CPython中的實(shí)現(xiàn)方式
print 函數(shù)的實(shí)現(xiàn)
在CPython中,print函數(shù)的實(shí)現(xiàn)主要位于Modules/builtins.c文件中。print函數(shù)的實(shí)現(xiàn)會涉及到多個步驟,包括參數(shù)的處理、格式化字符串的創(chuàng)建以及最終的輸出。以下是print函數(shù)實(shí)現(xiàn)的一個簡化版本:
static PyObject *
builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"sep", "end", "file", "flush", NULL};
PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
// 解析參數(shù)和關(guān)鍵字參數(shù)
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:print", kwlist,
&sep, &end, &file, &flush)) {
return NULL;
}
// ... 參數(shù)處理邏輯 ...
// 獲取標(biāo)準(zhǔn)輸出
if (file == NULL || file == Py_None) {
file = PySys_GetObject("stdout");
// ...
}
// ... 單個或多個對象的輸出邏輯 ...
// 刷新輸出
if (PyObject_CallMethod(file, "flush", "") == NULL) {
return NULL;
}
Py_RETURN_NONE;
}
在這個簡化的例子中,builtin_print函數(shù)是print函數(shù)的底層實(shí)現(xiàn)。它接收可變數(shù)量的參數(shù),并且有默認(rèn)的分隔符和結(jié)束符。然后,它會創(chuàng)建一個格式化的輸出字符串,并使用write方法將其寫入到指定的文件對象中,通常是sys.stdout。
input 函數(shù)的實(shí)現(xiàn)
input函數(shù)的實(shí)現(xiàn)則位于Modules/_io/_iotextio.c文件中。input函數(shù)會從標(biāo)準(zhǔn)輸入讀取一行文本,并返回一個字符串對象。以下是input函數(shù)實(shí)現(xiàn)的一個簡化版本:
static PyObject *
builtin_input(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *result = NULL, *getline_func = NULL;
PyObject *stdin = PySys_GetObject("stdin");
// ... 參數(shù)處理邏輯 ...
getline_func = PyObject_GetAttrString(stdin, "readline");
if (getline_func == NULL) {
return NULL;
}
result = PyObject_CallObject(getline_func, NULL);
Py_DECREF(getline_func);
if (result == NULL) {
return NULL;
}
// 去除末尾的換行符
if (PyBytes_Check(result)) {
// ... 處理字節(jié)數(shù)據(jù) ...
} else if (PyUnicode_Check(result)) {
Py_ssize_t length;
length = PyUnicode_GET_LENGTH(result);
if (length == 0) {
Py_CLEAR(result);
} else {
// 去除\n或者\(yùn)r\n
PyObject *rstripped = PyUnicode_Substring(result, 0, length-1);
if (rstripped == NULL || PyUnicode_READY(rstripped) == -1) {
return NULL;
}
Py_SETREF(result, rstripped);
}
}
return result;
}
在這個例子中,builtin_input函數(shù)是input函數(shù)的底層實(shí)現(xiàn)。如果提供了提示字符串,它會先將其寫入標(biāo)準(zhǔn)輸出。然后,它會從標(biāo)準(zhǔn)輸入讀取一行文本,并返回該行文本(不包括結(jié)尾的換行符)。
推薦閱讀
第1章:Python基礎(chǔ)-Python的語法和基本概念
第1章:Python基礎(chǔ)-Python 3 數(shù)據(jù)類型詳解:數(shù)字、字符串、布爾值
