云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

5分钟掌握Python中的标准输入、标准输出、标准错误

jxf315 2025-02-17 12:36:40 教程文章 26 ℃

读取用户输入

从标准输入获取输入:

user_input = input("Impart your wisdom: ")
print(f"You shared: {user_input}")

2. 打印到标准输出

将消息打印到控制台:

print("Behold, the message of the ancients!")

3. 格式化打印

将变量优雅精确地编织进您的信息中:

name = "Merlin"
age = 300
print(f"{name}, of {age} years, speaks of forgotten lore.")

4. 从标准输入读取行

逐行从标准输入中去除空白字符:

import sys
for line in sys.stdin:
    print(f"Echo from the void: {line.strip()}")

5. 写入到标准错误输出

向标准错误输出发送消息:

import sys
sys.stderr.write("Beware! The path is fraught with peril.\n")

6. 重定向标准输出

将 STDOUT 重定向:

import sys
original_stdout = sys.stdout  # Preserve the original STDOUT
with open('mystic_log.txt', 'w') as f:
    sys.stdout = f  # Redirect STDOUT to a file
    print("This message is inscribed within the mystic_log.txt.")
sys.stdout = original_stdout  # Restore STDOUT to its original glory

7. 重定向标准错误输出

重定向标准错误:

import sys
with open('warnings.txt', 'w') as f:
    sys.stderr = f  # Redirect STDERR
    print("This warning is sealed within warnings.txt.", file=sys.stderr)

8. 提示输入密码

提示输入密码:

import getpass
secret_spell = getpass.getpass("Whisper the secret spell: ")

9. 命令行参数

与解析命令行参数一起工作:

import sys
# The script's name is the first argument, followed by those passed by the invoker
script, first_arg, second_arg = sys.argv
print(f"Invoked with the sacred tokens: {first_arg} and {second_arg}")

10. 使用 Argparse 进行复杂的命令行交互

添加描述和选项/参数:

import argparse
parser = argparse.ArgumentParser(description="Invoke the ancient scripts.")
parser.add_argument('spell', help="The spell to cast")
parser.add_argument('--power', type=int, help="The power level of the spell")
args = parser.parse_args()
print(f"Casting {args.spell} with power {args.power}")

Tags:

最近发表
标签列表