网站首页 > 技术文章 正文
读取用户输入
从标准输入获取输入:
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}")
- 上一篇: 小学生Python编程入门-5.输入与输出
- 下一篇: Python实现从键盘输入字符并写入磁盘文件
猜你喜欢
- 2025-04-24 「Python算术运算符」输入长和宽计算长方形的周长和面积
- 2025-04-24 用python编写判断输入是否为整数的程序
- 2025-04-24 Python实现从键盘输入字符并写入磁盘文件
- 2025-04-24 小学生Python编程入门-5.输入与输出
- 2025-04-24 Python标准输入与标准输出
- 2025-04-24 冰冰讲Python(输入函数)
- 263℃Python短文,Python中的嵌套条件语句(六)
- 263℃python笔记:for循环嵌套。end=""的作用,图形打印
- 261℃PythonNet:实现Python与.Net代码相互调用!
- 256℃Python实现字符串小写转大写并写入文件
- 255℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 116℃原来2025是完美的平方年,一起探索六种平方的算吧
- 96℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 89℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)