Hướng dẫn redirect stdout python - redirect stdout python

Có chức năng

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
7 trong Python 3.4+:

Nội dung chính ShowShow

  • 2> là ký hiệu chuyển hướng đầu vào và cú pháp là:.
  • 2. Sử dụng import os from contextlib import redirect_stdout stdout_fd = sys.stdout.fileno[] with open['output.txt', 'w'] as f, redirect_stdout[f]: print['redirected to a file'] os.write[stdout_fd, b'not redirected'] os.system['echo this also is not redirected'] 2
  • 3. Sử dụng hàm contextlib.redirect_stdout[]
  • 4. Lớp đăng nhập tùy chỉnh
  • Làm cách nào để chuyển hướng một stdout đến một tệp trong Python?
  • Làm cách nào để chuyển hướng đầu ra tiêu chuẩn đến một tệp?
  • Làm thế nào để bạn xác định stdout trong python?
  • Làm thế nào để bạn chuyển hướng lỗi tiêu chuẩn và đầu ra tiêu chuẩn sang một tệp?

from contextlib import redirect_stdout

with open['help.txt', 'w'] as f:
    with redirect_stdout[f]:
        print['it now prints to `help.text`']

Nó tương tự như:

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value

có thể được sử dụng trên các phiên bản Python trước đó. Phiên bản thứ hai không thể tái sử dụng. Nó có thể được thực hiện một nếu muốn.

Nó không chuyển hướng stdout ở cấp độ mô tả tệp, ví dụ::

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
8 và

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
0 không được chuyển hướng đến tệp
import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
1.

Để chuyển hướng ở cấp độ mô tả tệp,

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
2 có thể được sử dụng:
import os
import sys
from contextlib import contextmanager

def fileno[file_or_fd]:
    fd = getattr[file_or_fd, 'fileno', lambda: file_or_fd][]
    if not isinstance[fd, int]:
        raise ValueError["Expected a file [`.fileno[]`] or a file descriptor"]
    return fd

@contextmanager
def stdout_redirected[to=os.devnull, stdout=None]:
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno[stdout]
    # copy stdout_fd before it is overwritten
    #NOTE: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen[os.dup[stdout_fd], 'wb'] as copied: 
        stdout.flush[]  # flush library buffers that dup2 knows nothing about
        try:
            os.dup2[fileno[to], stdout_fd]  # $ exec >&to
        except ValueError:  # filename
            with open[to, 'wb'] as to_file:
                os.dup2[to_file.fileno[], stdout_fd]  # $ exec > to
        try:
            yield stdout # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            #NOTE: dup2 makes stdout_fd inheritable unconditionally
            stdout.flush[]
            os.dup2[copied.fileno[], stdout_fd]  # $ exec >&copied

Ví dụ tương tự hoạt động bây giờ nếu

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
3 được sử dụng thay vì
import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
4:
import os
import sys

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, stdout_redirected[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'it is redirected now\n']
    os.system['echo this is also redirected']
print['this is goes back to stdout']

Đầu ra mà trước đây đã được in trên stdout bây giờ được chuyển đến

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
1 miễn là trình quản lý bối cảnh
import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
3 đang hoạt động.

Lưu ý:

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
7 không xóa C STDIO bộ đệm trên Python 3 trong đó I/O được triển khai trực tiếp trên các cuộc gọi hệ thống ________ 18/________ 19. Để xóa tất cả các luồng đầu ra stdio C mở, bạn có thể gọi
import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
0 rõ ràng nếu một số tiện ích mở rộng C sử dụng I/O dựa trên stdio:
import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
4

Bạn có thể sử dụng tham số

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
1 để chuyển hướng các luồng khác, không chỉ
import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
2 ví dụ, để hợp nhất
import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
3 và
import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
2:
import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
9

Example:

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
0

LƯU Ý:

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
3 trộn I/O được đệm [
import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
2 thường] và I/O không bị ảnh hưởng [hoạt động trên các mô tả tệp trực tiếp]. Coi chừng, có thể có vấn đề đệm.

Để trả lời, chỉnh sửa của bạn: Bạn có thể sử dụng

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
7 để trình bày tập lệnh của mình và sử dụng mô-đun
import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
8 [như @ERIKB85 được đề xuất] thay vì các câu lệnh ____29 và chỉ chuyển hướng STDout cho tập lệnh Python chạy dài của bạn mà bạn chạy ngay bây giờ.

Một đối tượng tệp tích hợp tương tự như luồng đầu ra tiêu chuẩn của trình thông dịch trong Python. Stdout được sử dụng để hiển thị đầu ra trực tiếp vào bảng điều khiển màn hình. Đầu ra có thể thuộc bất kỳ hình thức nào, nó có thể là đầu ra từ một câu lệnh in, câu lệnh biểu thức và thậm chí là một trực tiếp nhanh chóng cho đầu vào.

Làm thế nào để bạn chuyển hướng lỗi tiêu chuẩn và đầu ra tiêu chuẩn sang một tệp?

2> là ký hiệu chuyển hướng đầu vào và cú pháp là:.

Nó tương tự như:

có thể được sử dụng trên các phiên bản Python trước đó. Phiên bản thứ hai không thể tái sử dụng. Nó có thể được thực hiện một nếu muốn.

2. Sử dụng import os from contextlib import redirect_stdout stdout_fd = sys.stdout.fileno[] with open['output.txt', 'w'] as f, redirect_stdout[f]: print['redirected to a file'] os.write[stdout_fd, b'not redirected'] os.system['echo this also is not redirected'] 2

Nó không chuyển hướng stdout ở cấp độ mô tả tệp, ví dụ::

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno[]
with open['output.txt', 'w'] as f, redirect_stdout[f]:
    print['redirected to a file']
    os.write[stdout_fd, b'not redirected']
    os.system['echo this also is not redirected']
8 và

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
0 không được chuyển hướng đến tệp
import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
1.sys

path='path/to/some/dir/file.txt'='path/to/some/dir/file.txt'='path/to/some/dir/file.txt'

sys.stdout=open[path,'w'].stdout=open[path,'w'].stdout=open[path,'w']

Để chuyển hướng ở cấp độ mô tả tệp, ['Hello, World']

có thể được sử dụng trên các phiên bản Python trước đó. Phiên bản thứ hai không thể tái sử dụng. Nó có thể được thực hiện một nếu muốn.

3. Sử dụng hàm contextlib.redirect_stdout[]

4. Lớp đăng nhập tùy chỉnh

Làm cách nào để chuyển hướng một stdout đến một tệp trong Python?

Làm cách nào để chuyển hướng đầu ra tiêu chuẩn đến một tệp?contextlib

path='path/to/some/dir/file.txt'='path/to/some/dir/file.txt'='path/to/some/dir/file.txt'

withopen[path,'w']asf:open[path,'w']asf:open[path,'w']asf:

    withcontextlib.redirect_stdout[f]:withcontextlib.redirect_stdout[f]:withcontextlib.redirect_stdout[f]:

Làm thế nào để bạn xác định stdout trong python?print['Hello, World']

có thể được sử dụng trên các phiên bản Python trước đó. Phiên bản thứ hai không thể tái sử dụng. Nó có thể được thực hiện một nếu muốn.

4. Lớp đăng nhập tùy chỉnh

Làm cách nào để chuyển hướng một stdout đến một tệp trong Python?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
0 không được chuyển hướng đến tệp
import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout[new_target]:
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value
1.sys

classLogger:Logger:Logger:

    def__init__[self,filename]:def__init__[self,filename]:def__init__[self,filename]:

        self.console=sys.stdoutself.console=sys.stdoutself.console=sys.stdout

        self.file=open[filename,'w']self.file=open[filename,'w']self.file=open[filename,'w']

    defwrite[self,message]:defwrite[self,message]:defwrite[self,message]:

        self.console.write[message]self.console.write[message]self.console.write[message]

        self.file.write[message]self.file.write[message]self.file.write[message]

    defflush[self]:defflush[self]:def flush[self]:

        self.console.flush[]self.console.flush[]self.console.flush[]

        self.file.flush[]self.file.flush[]self.file.flush[]

path='path/to/some/dir/file.txt'='path/to/some/dir/file.txt'='path/to/some/dir/file.txt'

sys.stdout=Logger[path].stdout=Logger[path].stdout=Logger[path]

In ['Xin chào, Thế giới']['Hello, World']['Hello, World']

Tải xuống mã

Đó là tất cả về việc chuyển hướng đầu ra tiêu chuẩn sang một tệp trong Python.

Cảm ơn vì đã đọc.

Vui lòng sử dụng trình biên dịch trực tuyến của chúng tôi để đăng mã trong các nhận xét bằng C, C ++, Java, Python, JavaScript, C#, PHP và nhiều ngôn ngữ lập trình phổ biến hơn.

Như chúng tôi? Giới thiệu chúng tôi với bạn bè của bạn và giúp chúng tôi phát triển. Mã hóa hạnh phúc :] :] :]


Làm cách nào để chuyển hướng một stdout đến một tệp trong Python?

Tuy nhiên, bạn có thể chuyển hướng đầu ra đó vào một tệp bằng bất kỳ chức năng nào sau đây:...

Chuyển hướng vỏ. Cách tiếp cận phổ biến nhất để chuyển hướng đầu ra tiêu chuẩn sang tệp là sử dụng chuyển hướng shell. ....

Sử dụng sys.stdout. ....

Sử dụng hàm bối cảnh.Redirect_stdout []. ....

Lớp đăng nhập tùy chỉnh ..

Làm cách nào để chuyển hướng đầu ra tiêu chuẩn đến một tệp?

Chuyển hướng STDOUT và STDERR sang tệp: Các luồng I/O có thể được chuyển hướng bằng cách sử dụng toán tử N>, trong đó n là số mô tả tệp.Để chuyển hướng STDOUT, chúng tôi sử dụng 1>> và đối với Stderr, thì 2> được thêm vào làm toán tử.For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.

Làm thế nào để bạn xác định stdout trong python?

Một đối tượng tệp tích hợp tương tự như luồng đầu ra tiêu chuẩn của trình thông dịch trong Python.Stdout được sử dụng để hiển thị đầu ra trực tiếp vào bảng điều khiển màn hình.Đầu ra có thể thuộc bất kỳ hình thức nào, nó có thể là đầu ra từ một câu lệnh in, câu lệnh biểu thức và thậm chí là một trực tiếp nhanh chóng cho đầu vào.. stdout is used to display output directly to the screen console. Output can be of any form, it can be output from a print statement, an expression statement, and even a prompt direct for input.. stdout is used to display output directly to the screen console. Output can be of any form, it can be output from a print statement, an expression statement, and even a prompt direct for input.

Làm thế nào để bạn chuyển hướng lỗi tiêu chuẩn và đầu ra tiêu chuẩn sang một tệp?

2> là ký hiệu chuyển hướng đầu vào và cú pháp là:...

Để chuyển hướng stderr [lỗi tiêu chuẩn] sang tệp: lệnh 2> error.txt ..

Hãy để chúng tôi chuyển hướng cả stderr và stdout [đầu ra tiêu chuẩn]: lệnh &> oput.txt ..

Cuối cùng, chúng ta có thể chuyển hướng stdout sang một tệp có tên myOutput.txt, sau đó chuyển hướng stderr sang stdout bằng 2> & 1 [error.txt]:.

Bài Viết Liên Quan

Chủ Đề