杰瑞科技汇

Python如何使用stdin与stdout进行输入输出?

Of course! This is a fundamental concept in programming, especially for competitive programming, scripting, and automating command-line tasks.

Python如何使用stdin与stdout进行输入输出?-图1
(图片来源网络,侵删)

Let's break down stdin and stdout in Python, from the basics to more advanced usage.

The Core Idea: Standard Streams

Imagine your computer as a system that processes information. It needs a way to get input and a way to send output.

  • Standard Input (stdin): The default source for input data. By default, this is your keyboard.
  • Standard Output (stdout): The default destination for normal program output. By default, this is your terminal/console/screen.
  • Standard Error (stderr): A separate stream for error messages. By default, this is also your terminal, but it allows you to separate normal output from errors.

In Python, these streams are represented by three built-in objects, all available in the sys module:

Stream Python Object Default Source/Destination
Standard Input sys.stdin Keyboard
Standard Output sys.stdout Terminal/Screen
Standard Error sys.stderr Terminal/Screen

Method 1: The "Pythonic" Way (Using input() and print())

For most everyday scripts, you don't need to touch sys.stdin and sys.stdout directly. Python provides high-level, user-friendly functions that use these streams behind the scenes.

Python如何使用stdin与stdout进行输入输出?-图2
(图片来源网络,侵删)

Reading Input (stdin)

The input() function reads a single line from sys.stdin.

# This script waits for you to type something and press Enter.
# It then prints what you typed.
name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hello, {name}! Next year you will be {age + 1} years old.")

How to run it:

  1. Save the code as greet.py.
  2. Run it from your terminal: python greet.py
  3. The terminal will pause, waiting for your keyboard input.

Writing Output (stdout)

The print() function sends its arguments to sys.stdout. By default, it adds a newline character (\n) at the end.

# This script prints three lines of text to the terminal.
print("This is the first line.")
print("This is the second line.")
print("And this is the third.")

Method 2: The Direct & Powerful Way (Using sys.stdin and sys.stdout)

This method is essential for reading multiple lines of input efficiently (e.g., in a loop) or for more granular control over output.

Python如何使用stdin与stdout进行输入输出?-图3
(图片来源网络,侵删)

Reading from sys.stdin

The sys.stdin object is a file-like object. This means you can use methods like .read(), .readline(), and loop over it directly.

Key Methods:

  • sys.stdin.read(): Reads the entire input at once until an EOF (End-Of-File) character is sent. This is useful for getting all input as a single string.
  • sys.stdin.readline(): Reads one line from the input, including the trailing newline character (\n). This is very efficient for line-by-line processing.
  • for line in sys.stdin:: A clean and Pythonic way to loop through all lines in the input until EOF. This is often the best choice.

Example 1: Reading all input at once

import sys
# This script will read everything you type until you send an EOF signal.
# On Linux/macOS, send EOF with Ctrl+D. On Windows, it's Ctrl+Z then Enter.
data = sys.stdin.read()
print("--- End of Input ---")
print(f"You entered {len(data)} characters.")
print(f"Content:\n{data}")

Example 2: Reading line by line in a loop (Very Common)

This is a pattern you'll see often in competitive programming and data processing scripts.

import sys
print("Enter your text. Press Ctrl+D (Linux/macOS) or Ctrl+Z (Windows) to finish.")
# This loop will continue until there is no more input (EOF)
for line in sys.stdin:
    # The 'line' variable includes the newline character, so we use .strip() to remove it
    processed_line = line.strip().upper()
    print(f"Processed: {processed_line}")
print("Input finished.")

Writing to sys.stdout

Just like sys.stdin, sys.stdout is a file-like object. You can use methods like .write().

  • sys.stdout.write("some text"): Writes the string to the output. Crucially, it does not add a newline by default. You must add \n if you want one.

Example: Using sys.stdout.write()

import sys
# Notice we have to add the newline character (\n) ourselves
sys.stdout.write("Hello from stdout.write() ")
sys.stdout.write("without a newline.\n")
name = "Alice"
age = 30
# This is how you can build formatted strings without print()
output_string = f"My name is {name} and I am {age}.\n"
sys.stdout.write(output_string)

When to use sys.stdout.write()?

  • When you don't want the automatic newline that print() adds.
  • When you need to flush the output buffer immediately (using sys.stdout.flush()), which is useful in real-time applications.
  • For performance-critical applications where the overhead of print() is noticeable (though this is rare).

Putting It All Together: A Practical Example

Let's create a script that processes a list of numbers from stdin.

Scenario:

  1. The script expects numbers, one per line.
  2. It should read each number, square it, and print the result.
  3. It should stop when it receives EOF.

Solution:

import sys
print("Enter numbers, one per line. Press Ctrl+D to finish.")
for line in sys.stdin:
    # .strip() removes leading/trailing whitespace (like the newline \n)
    # .isdigit() checks if the string consists only of digits
    if line.strip().isdigit():
        number = int(line.strip())
        squared = number * number
        # Using print() here is perfectly fine and readable
        print(f"The square of {number} is {squared}")
    else:
        # This part is optional, but good for robustness
        print(f"Skipping invalid input: '{line.strip()}'")
print("\nProcessing complete.")

How to run this script:

  1. Save it as square_numbers.py.
  2. Run it: python square_numbers.py
  3. Start typing numbers and pressing Enter:
    5
    10
    hello
    3
  4. Send the EOF signal (Ctrl+D).
  5. You will see the output in your terminal.

Redirection: The Real Power of stdin and stdout

The true power of these streams is that you can easily redirect them from and to files without changing your Python code.

Redirecting stdin from a file: Use the < operator.

# Let's say you have a file named 'numbers.txt' with:
# 1
# 2
# 3
# 4
# Run the script, but take input from 'numbers.txt' instead of the keyboard
python square_numbers.py < numbers.txt

Output:

The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
Processing complete.

Redirecting stdout to a file: Use the > operator to overwrite or >> to append.

# Run the script and save its normal output to 'results.txt'
python square_numbers.py < numbers.txt > results.txt
# Now, 'results.txt' will contain the squared numbers.
# The output will not appear on your screen because it was redirected.
# To append to a file instead of overwriting:
python square_numbers.py < numbers.txt >> results.txt

This separation of logic (your code) from data source (keyboard/file) and data destination (screen/file) is a cornerstone of Unix-like philosophy and makes your scripts incredibly versatile.

Summary: print() vs sys.stdout.write()

Feature print() sys.stdout.write()
Usage High-level, general purpose Low-level, granular control
Newline Automatically adds a \n Does not add a \n (you must)
Multiple Args print(a, b, c) is valid write() takes only one string
end param print(..., end='') can change the ending No such parameter; must include it in the string
file param print(..., file=sys.stderr) can redirect output More direct way to write to a specific stream
When to use 99% of the time. It's simpler, more readable, and what most Python developers expect. When you need precise control (no newline, flushing), or for performance in extreme cases.
分享:
扫描分享到社交APP
上一篇
下一篇