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

B站影视 2025-02-09 14:22 3

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

从标准输入获取输入:

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

将消息打印到控制台:

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

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

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

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

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

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

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

将 STDOUT 重定向:

import sysoriginal_stdout = sys.stdout # Preserve the original STDOUTwith 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

重定向标准错误:

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

提示输入密码:

import getpasssecret_spell = getpass.getpass("Whisper the secret spell: ")import sys# The script's name is the first argument, followed by those passed by the invokerscript, first_arg, second_arg = sys.argvprint(f"Invoked with the sacred tokens: {first_arg} and {second_arg}")import argparseparser = 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_argsprint(f"Casting {args.spell} with power {args.power}")

来源:自由坦荡的湖泊AI

相关推荐