精华内容
下载资源
问答
  • 今天小编就为大家分享一篇Python中的sys.stdout.write实现打印刷新功能,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • 你的程序中有个方法会输出到标准输出中(sys.stdout)。也就是说它会将文本打印到屏幕上面。 你想写个测试来证明它,给定一个输入,相应的输出能正常显示出来。 解决方案 使用 unittest.mock 模块中的 patch() 函数...
  • cli-tty-tty 模块但TTY。 它提供了cli-color兼容的API,该API不会为非TTY使用而为您的字符串着色。 例子 var clc = require ( 'cli-color-tty' ) ( true ) // clc is = require('cli-color') ...
  • supervisor-stdout-源码

    2021-05-24 08:39:28
    pip install supervisor-stdout 用法 一个示例supervisord.conf: [supervisord] nodaemon = true [program:web] command = ... stdout_events_enabled = true stderr_events_enabled = true [eventlistener:...
  • movipy输出文件时报错 ‘NoneType’ object has no attribute ‘stdout’问题,经确认是moviepy版本本身的bug,一般情况下不会触发,可能是执行AudioFileClip.close()时报错。 经查阅《github/Zulko/moviepy》有该...
  • 一、sys.stdout的形式就是print的一种默认输出格式,等于print “%VALUE%” print函数是对sys.stdout的高级封装,看下print函数的解释 Prints the values to a stream, or to sys.stdout by default. Optional ...
  • 《算法》中,使用StdOut.printf () 语句需要的algs4.jar文件 下载及配置。《算法》第四版的jar包08-02 《算法(第4版)》是Sedgewick之巨著,与高德纳TAOCP一脉相承,是算法领域经典的参考书,涵盖所有程序员必须掌握...
  • websocketd是一个小型命令行工具,它将包装现有的命令行界面程序,并允许通过WebSocket访问它。
  • 主要介绍了详解使用python的logging模块在stdout输出的相关资料,需要的朋友可以参考下
  • ,使用stdout的消息和stderr的错误。 安装 使用 : npm install --save-dev jest-standard-reporter 使用: yarn add --dev jest-standard-reporter 用法 Jest CLI: jest --reporters=jest-standard-reporter 开...
  • 今天小编就为大家分享一篇 python-sys.stdout作为默认函数参数的实现,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • 简约的Golang记录器,可记录到stdout和文件。 安装 go get github.com/munirehmad/golanglog 用法 package main import ( "github.com/munirehmad/golanglog" ) func main(){ log := golanglog.NewLogger("./logs...
  • 将结果流式传输到stdout的psql-esque CLI 安装 使用全局安装: $ npm install psql-stream -g 用法 Usage: psql-stream [options] psql-esque CLI that streams results to stdout Options: -c, --command SQL ...
  • ucrt_crash_on_printf:在_setmode(_fileno(stdout),_O_U8TEXT)之后,使用printf会使程序崩溃
  • jpypaths 将Jupyter路径列表转储到stdout 跑步 python jpypaths.py
  • JAVA StdOut工具类下载

    2019-04-18 10:49:58
    分享一个JAVA StdOut的工具类,此工具类主要用于输出等一系列变换,推荐大家在我博客百度云盘下载。
  • How do I redirect stdout to an arbitrary file in Python? 如何在Python中将stdout重定向到任意文件? When a long-r

    本文翻译自:Redirect stdout to a file in Python?

    How do I redirect stdout to an arbitrary file in Python? 如何在Python中将stdout重定向到任意文件?

    When a long-running Python script (eg, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write to stdout. 当从ssh会话中启动运行了长时间的Python脚本(例如,Web应用程序)并进行背景调整,并且ssh会话关闭时,该应用程序将在尝试写入stdout时引发IOError并失败。 I needed to find a way to make the application and modules output to a file rather than stdout to prevent failure due to IOError. 我需要找到一种方法来使应用程序和模块输出到文件而不是stdout,以防止由于IOError而导致失败。 Currently, I employ nohup to redirect output to a file, and that gets the job done, but I was wondering if there was a way to do it without using nohup, out of curiosity. 当前,我使用nohup将输出重定向到文件,并且可以完成工作,但是我想知道是否有一种出于好奇而无需使用nohup的方法。

    I have already tried sys.stdout = open('somefile', 'w') , but this does not seem to prevent some external modules from still outputting to terminal (or maybe the sys.stdout = ... line did not fire at all). 我已经尝试过sys.stdout = open('somefile', 'w') ,但这似乎并不能阻止某些外部模块仍然输出到终端(或者sys.stdout = ...行未在所有)。 I know it should work from simpler scripts I've tested on, but I also didn't have time yet to test on a web application yet. 我知道它应该可以通过我测试过的简单脚本工作,但是我还没有时间在Web应用程序上进行测试。


    #1楼

    参考:https://stackoom.com/question/jCmY/将stdout重定向到Python中的文件


    #2楼

    The other answers didn't cover the case where you want forked processes to share your new stdout. 其他答案没有涉及您希望分叉的进程共享新标准输出的情况。

    To do that: 要做到这一点:

    from os import open, close, dup, O_WRONLY
    
    old = dup(1)
    close(1)
    open("file", O_WRONLY) # should open on 1
    
    ..... do stuff and then restore
    
    close(1)
    dup(old) # should dup to 1
    close(old) # get rid of left overs
    

    #3楼

    Quoted from PEP 343 -- The "with" Statement (added import statement): 引用自PEP 343-“ with”语句 (添加的导入语句):

    Redirect stdout temporarily: 暂时重定向标准输出:

    import sys
    from contextlib import contextmanager
    @contextmanager
    def stdout_redirected(new_stdout):
        save_stdout = sys.stdout
        sys.stdout = new_stdout
        try:
            yield None
        finally:
            sys.stdout = save_stdout
    

    Used as follows: 用法如下:

    with open(filename, "w") as f:
        with stdout_redirected(f):
            print "Hello world"
    

    This isn't thread-safe, of course, but neither is doing this same dance manually. 当然,这不是线程安全的,但是也没有手动进行相同的舞蹈。 In single-threaded programs (for example in scripts) it is a popular way of doing things. 在单线程程序中(例如在脚本中),这是一种流行的处理方式。


    #4楼

    Programs written in other languages (eg C) have to do special magic (called double-forking) expressly to detach from the terminal (and to prevent zombie processes). 用其他语言(例如C)编写的程序必须做特别的魔术(称为双叉)才能与终端分离(并防止僵尸进程)。 So, I think the best solution is to emulate them. 因此,我认为最好的解决方案是模仿它们。

    A plus of re-executing your program is, you can choose redirections on the command-line, eg /usr/bin/python mycoolscript.py 2>&1 1>/dev/null 重新执行程序的一个/usr/bin/python mycoolscript.py 2>&1 1>/dev/null是,您可以在命令行上选择重定向,例如/usr/bin/python mycoolscript.py 2>&1 1>/dev/null

    See this post for more info: What is the reason for performing a double fork when creating a daemon? 有关更多信息,请参见此帖子: 创建守护程序时执行双叉的原因是什么?


    #5楼

    There is contextlib.redirect_stdout() function in Python 3.4: Python 3.4中有contextlib.redirect_stdout()函数

    from contextlib import redirect_stdout
    
    with open('help.txt', 'w') as f:
        with redirect_stdout(f):
            print('it now prints to `help.text`')
    

    It is similar to: 它类似于:

    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
    

    that can be used on earlier Python versions. 可以在早期的Python版本中使用。 The latter version is not reusable . 后一版本不可重用 It can be made one if desired. 如果需要,可以将其制成一个。

    It doesn't redirect the stdout at the file descriptors level eg: 它不会在文件描述符级别重定向标准输出,例如:

    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')
    

    b'not redirected' and 'echo this also is not redirected' are not redirected to the output.txt file. b'not redirected''echo this also is not redirected'未重定向到output.txt文件。

    To redirect at the file descriptor level, os.dup2() could be used: 要在文件描述符级别重定向,可以使用os.dup2()

    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
    

    The same example works now if stdout_redirected() is used instead of redirect_stdout() : 如果使用stdout_redirected()而不是redirect_stdout()则现在可以使用相同的示例:

    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')
    

    The output that previously was printed on stdout now goes to output.txt as long as stdout_redirected() context manager is active. 只要上下文管理器stdout_redirected()处于活动状态,以前打印在stdout上的输出现在将进入output.txt

    Note: stdout.flush() does not flush C stdio buffers on Python 3 where I/O is implemented directly on read() / write() system calls. 注意: stdout.flush()不会刷新Python 3上的C stdio缓冲区,在该Python 3上,I / O是直接在read() / write()系统调用上实现的。 To flush all open C stdio output streams, you could call libc.fflush(None) explicitly if some C extension uses stdio-based I/O: 要刷新所有打开的C stdio输出流,如果某些C扩展使用基于stdio的I / O,则可以显式调用libc.fflush(None)

    try:
        import ctypes
        from ctypes.util import find_library
    except ImportError:
        libc = None
    else:
        try:
            libc = ctypes.cdll.msvcrt # Windows
        except OSError:
            libc = ctypes.cdll.LoadLibrary(find_library('c'))
    
    def flush(stream):
        try:
            libc.fflush(None)
            stream.flush()
        except (AttributeError, ValueError, IOError):
            pass # unsupported
    

    You could use stdout parameter to redirect other streams, not only sys.stdout eg, to merge sys.stderr and sys.stdout : 您可以使用stdout参数重定向其他流,而不仅仅是sys.stdout例如,合并sys.stderrsys.stdout

    def merged_stderr_stdout():  # $ exec 2>&1
        return stdout_redirected(to=sys.stdout, stdout=sys.stderr)
    

    Example: 例:

    from __future__ import print_function
    import sys
    
    with merged_stderr_stdout():
         print('this is printed on stdout')
         print('this is also printed on stdout', file=sys.stderr)
    

    Note: stdout_redirected() mixes buffered I/O ( sys.stdout usually) and unbuffered I/O (operations on file descriptors directly). 注意: stdout_redirected()将缓冲的I / O(通常为sys.stdout )和无缓冲的I / O(直接对文件描述符的操作)混合使用。 Beware, there could be buffering issues . 当心,可能存在缓冲 问题

    To answer, your edit: you could use python-daemon to daemonize your script and use logging module (as @erikb85 suggested ) instead of print statements and merely redirecting stdout for your long-running Python script that you run using nohup now. 要回答,请进行编辑:您可以使用python-daemon并使用logging模块(如@ erikb85建议 )代替print语句,而仅将stdout重定向为您现在使用nohup运行的长期运行的Python脚本。


    #6楼

    Based on this answer: https://stackoverflow.com/a/5916874/1060344 , here is another way I figured out which I use in one of my projects. 基于以下答案: https : //stackoverflow.com/a/5916874/1060344 ,这是我想出在我的一个项目中使用的另一种方法。 For whatever you replace sys.stderr or sys.stdout with, you have to make sure that the replacement complies with file interface, especially if this is something you are doing because stderr/stdout are used in some other library that is not under your control. 对于用sys.stderrsys.stdout替换的任何内容,都必须确保替换符合file接口,尤其是在执行此操作时,因为stderr / stdout用于其他不受您控制的库中。 That library may be using other methods of file object. 该库可能正在使用文件对象的其他方法。

    Check out this way where I still let everything go do stderr/stdout (or any file for that matter) and also send the message to a log file using Python's logging facility (but you can really do anything with this): 看看这种方式,我仍然可以让所有事情继续进行stderr / stdout(或与此有关的任何文件),并使用Python的日志记录工具将消息发送到日志文件中(但您实际上可以执行任何操作):

    class FileToLogInterface(file):
        '''
        Interface to make sure that everytime anything is written to stderr, it is
        also forwarded to a file.
        '''
    
        def __init__(self, *args, **kwargs):
            if 'cfg' not in kwargs:
                raise TypeError('argument cfg is required.')
            else:
                if not isinstance(kwargs['cfg'], config.Config):
                    raise TypeError(
                        'argument cfg should be a valid '
                        'PostSegmentation configuration object i.e. '
                        'postsegmentation.config.Config')
            self._cfg = kwargs['cfg']
            kwargs.pop('cfg')
    
            self._logger = logging.getlogger('access_log')
    
            super(FileToLogInterface, self).__init__(*args, **kwargs)
    
        def write(self, msg):
            super(FileToLogInterface, self).write(msg)
            self._logger.info(msg)
    
    展开全文
  • jsonexec 运行命令并将输出(stdout)JSON转换为提供的对象
  • Ansible Stdout紧凑型记录仪 安装 放在磁盘上的某个地方 在您的ansible配置的[defaults]设置中添加callback_plugins设置 将stdout_callback更改为anstomlog cf ansible.cfg 。 产品特点 单行显示 兼容pylint...
  • Fatmawati Achmad Zaenuri/Shutterstock.comFatmawati Achmad Zaenuri / Shutterstock.com stdin, stdout, and stderr are three data streams created when you launch a Linux command. You can use them to tell ...
    Terminal window on a Linux computer
    Fatmawati Achmad Zaenuri/Shutterstock.com Fatmawati Achmad Zaenuri / Shutterstock.com

    stdin, stdout, and stderr are three data streams created when you launch a Linux command. You can use them to tell if your scripts are being piped or redirected. We show you how.

    stdinstdoutstderr是启动Linux命令时创建的三个数据流。 您可以使用它们来告诉您的脚本是通过管道传输还是重定向。 我们向您展示如何。

    流连接两点 (Streams Join Two Points)

    As soon as you start to learn about Linux and Unix-like operating systems, you’ll come across the terms stdin, stdout, and stederr. These are three standard streams that are established when a Linux command is executed. In computing, a stream is something that can transfer data. In the case of these streams, that data is text.

    一旦您开始了解Linux和类似Unix的操作系统,就会遇到术语stdinstdoutstederr 。 这是执行Linux命令时建立的三个标准流 。 在计算中,流是可以传输数据的东西。 对于这些流,该数据是文本。

    Data streams, like water streams, have two ends. They have a source and an outflow. Whichever Linux command you’re using provides one end of each stream. The other end is determined by the shell that launched the command. That end will be connected to the terminal window, connected to a pipe, or redirected to a file or other command, according to the command line that launched the command.

    数据流就像水流一样,有两个末端。 他们有一个来源和一个流出。 您所使用的任何Linux命令都提供每个流的一端。 另一端由启动命令的外壳程序确定。 根据启动命令的命令行,该端将连接到终端窗口,连接到管道或重定向到文件或其他命令。

    Linux标准流 (The Linux Standard Streams)

    In Linux, stdin is the standard input stream. This accepts text as its input. Text output from the command to the shell is delivered via the stdout (standard out) stream. Error messages from the command are sent through the stderr (standard error) stream.

    在Linux中, stdin是标准输入流。 这接受文本作为输入。 从命令输出到外壳的文本是通过stdout (标准输出)流传递的。 命令的错误消息通过stderr (标准错误)流发送。

    So you can see that there are two output streams, stdout and stderr, and one input stream, stdin. Because error messages and normal output each have their own conduit to carry them to the terminal window, they can be handled independently of one another.

    因此,您可以看到有两个输出流stdoutstderr ,以及一个输入流stdin 。 由于错误消息和正常输出各自具有将其携带到终端窗口的管道,因此可以彼此独立地进行处理。

    流像文件一样处理 (Streams Are Handled Like Files)

    Streams in Linux—like almost everything else—are treated as though they were files. You can read text from a file, and you can write text into a file. Both of these actions involve a stream of data. So the concept of handling a stream of data as a file isn’t that much of a stretch.

    与几乎所有其他内容一样,Linux中的流被视为文件。 您可以从文件中读取文本,也可以将文本写入文件中。 这两个动作都涉及数据流。 因此,将数据流作为文件处理的概念并不是一件容易的事。

    Each file associated with a process is allocated a unique number to identify it. This is known as the file descriptor. Whenever an action is required to be performed on a file, the file descriptor is used to identify the file.

    与进程关联的每个文件都分配有一个唯一的编号以进行标识。 这称为文件描述符。 每当需要对文件执行操作时, 文件描述符都用于标识文件。

    These values are always used for stdin, stdout, and stderr:

    这些值始终用于stdinstdout,stderr

    • 0: stdin

      0 :标准输入

    • 1: stdout

      1 :标准输出

    • 2: stderr

      2 :标准错误

    对管道和重定向做出React (Reacting to Pipes and Redirects)

    To ease someone’s introduction to a subject, a common technique is to teach a simplified version of the topic. For example, with grammar, we are told that the rule is “I before E, except after C.” But actually, there are more exceptions to this rule than there are cases that obey it.

    为了简化某人对该主题的介绍,一种常见的技术是教授该主题的简化版本。 例如,对于语法,我们被告知该规则是“ E在E之前,C之后”。 但是实际上,与遵守此规则的情况相比,此规则有更多例外

    In a similar vein, when talking about stdin, stdout, and stderr it is convenient to trot out the accepted axiom that a process neither knows nor cares where its three standard streams are terminated. Should a process care whether its output is going to the terminal or being redirected into a file? Can it even tell if its input is coming from the keyboard or is being piped into it from another process?

    同样,在谈论stdinstdoutstderr ,很方便地抛出公认的公理,该公理既不知道也不关心进程的三个标准流在哪里终止。 进程是否应该关心其输出是要发送到终端还是重定向到文件? 它甚至可以判断其输入是来自键盘还是正从另一个进程通过管道输入?

    Actually, a process does know—or at least it can find out, should it choose to check—and it can change its behavior accordingly if the software author decided to add that functionality.

    实际上,如果软件作者决定添加该功能,则该过程确实知道(或者至少可以找到,应该选择检查),并且可以相应地更改其行为。

    We can see this change in behavior very easily. Try these two commands:

    我们可以很容易地看到这种行为上的变化。 尝试以下两个命令:

    ls
    
    ls in a terminal window
    ls | cat
    
    ls output in a terminal window

    The ls command behaves differently if its output (stdout) is being piped into another command. It is ls that switches to a single column output, it isn’t a conversion performed by cat. And ls does the same thing if its output is being redirected:

    如果将其输出( stdout )传递到另一个命令中,则ls命令的行为会有所不同。 是ls切换到单列输出,而不是cat进行的转换。 如果重定向其输出,则ls执行相同的操作:

    ls > capture.txt
    
    ls > capture.txt in a terminal window
    cat capture.txt
    
    cat capture.txt in a terminal window

    重定向标准输出和标准错误 (Redirecting stdout and stderr)

    There’s an advantage to having error messages delivered by a dedicated stream. It means we can redirect a command’s output (stdout) to a file and still see any error messages (stderr) in the terminal window. You can react to the errors if you need to, as they occur. It also stops the error messages from contaminating the file that stdout has been redirected into.

    通过专用流传递错误消息有一个优势。 这意味着我们可以将命令的输出( stdout )重定向到文件,并且仍然可以在终端窗口中看到任何错误消息( stderr )。 您可以根据需要对错误进行处理,以防发生错误。 它还可以防止错误消息污染已将stdout重定向到的文件。

    Type the following text into an editor and save it to a file called error.sh.

    在编辑器中键入以下文本,然后将其保存到名为error.sh的文件中。

    #!/bin/bash
    
    echo "About to try to access a file that doesn't exist"
    cat bad-filename.txt
    

    Make the script executable with this command:

    使用以下命令使脚本可执行:

    chmod +x error.sh
    

    The first line of the script echoes text to the terminal window, via the stdout stream. The second line tries to access a file that doesn’t exist. This will generate an error message that is delivered via stderr.

    脚本的第一行通过stdout流将文本回显到终端窗口。 第二行尝试访问不存在的文件。 这将生成一条错误消息,该消息通过stderr传递。

    Run the script with this command:

    使用以下命令运行脚本:

    ./error.sh
    
    ./error.sh in a terminal window

    We can see that both streams of output, stdout and stderr, have been displayed in the terminal windows.

    我们可以看到两个输出流stdoutstderr都已显示在终端窗口中。

    output from error.sh script in a terminal window

    Let’s try to redirect the output to a file:

    让我们尝试将输出重定向到文件:

    ./error.sh > capture.txt
    
    ./error.sh > capture.txt in a terminal window

    The error message that is delivered via stderr is still sent to the terminal window. We can check the contents of the file to see whether the stdout output went to the file.

    通过stderr传递的错误消息仍会发送到终端窗口。 我们可以检查文件的内容以查看stdout输出是否到达了文件。

    cat capture.txt
    
    cat capture.txt in a terminal window

    The output from stdin was redirected to the file as expected.

    stdin的输出已按预期重定向到文件。

    contents of capture.txt in a terminal window

    The > redirection symbol works with stdout by default. You can use one of the numeric file descriptors to indicate which standard output stream you wish to redirect.

    默认情况下, >重定向符号与stdout使用。 您可以使用数字文件描述符之一来指示要重定向的标准输出流。

    To explicitly redirect  stdout, use this redirection instruction:

    要显式重定向stdout ,请使用以下重定向指令:

    1>
    

    To explicitly redirect  stderr, use this redirection instruction:

    要显式重定向stderr ,请使用以下重定向指令:

    2>
    

    Let’s try to our test again, and this time we’ll use 2>:

    让我们再次尝试测试,这次我们将使用2>

    ./error.sh 2> capture.txt
    
    ./error.sh 2> capture.txt in a terminal window

    The error message is redirected and the stdout echo message is sent to the terminal window:

    重定向错误消息,并将stdout echo消息发送到终端窗口:

    output from ./error.sh 2> capture.txt in a terminal window

    Let’s see what is in the capture.txt file.

    让我们看看capture.txt文件中的内容。

    cat capture.txt
    
    cat capture.txt in a terminal window

    The stderr message is in capture.txt as expected.

    如预期的那样, stderr消息位于capture.txt中。

    contents of capture.txt file in a terminal window

    重定向stdout和stderr (Redirecting Both stdout and stderr)

    Surely, if we can redirect either stdout or stderr to a file independently of one another, we ought to be able to redirect them both at the same time, to two different files?

    当然,如果我们可以将stdoutstderr相互重定向到一个文件,那么我们应该能够同时将它们重定向到两个不同的文件吗?

    Yes, we can. This command will direct stdout to a file called capture.txt and stderr to a file called error.txt.

    我们可以。 此命令会将stdout定向到名为capture.txt的文件,并将stderr定向到名为error.txt的文件。

    ./error.sh 1> capture.txt 2> error.txt
    
    ./error.sh 1> capture.txt 2> error.txt in a terminal window

    Because both streams of output–standard output and standard error—are redirected to files, there is no visible output in the terminal window. We are returned to the command line prompt as though nothing has occurred.

    因为输出流(标准输出和标准错误)都被重定向到文件,所以终端窗口中没有可见的输出。 就像什么都没有发生一样,我们返回到命令行提示符。

    ./error.sh output in a terminal window

    Let’s check the contents of each file:

    让我们检查每个文件的内容:

    cat capture.txt
    
    cat error.txt
    
    contents of capture.txt and error.txt in a terminal window

    将stdout和stderr重定向到同一文件 (Redirecting stdout and stderr to the Same File)

    That’s neat, we’ve got each of the standard output streams going to its own dedicated file. The only other combination we can do is to send both stdout and stderr to the same file.

    太好了,我们已经将每个标准输出流放入其自己的专用文件中。 我们唯一可以做的其他组合是将stdoutstderr都发送到同一文件。

    We can achieve this with the following command:

    我们可以使用以下命令来实现:

    ./error.sh > capture.txt 2>&1
    

    Let’s break that down.

    让我们分解一下。

    • ./error.sh: Launches the error.sh script file.

      ./error.sh :启动error.sh脚本文件。

    • > capture.txt: Redirects the stdout stream to the capture.txt file. > is shorthand for 1>.

      > capture.txt :将stdout流重定向到capture.txt文件。 >1>简写。

    • 2>&1: This uses the &> redirect instruction. This instruction allows you to tell the shell to make one stream got to the same destination as another stream. In this case, we’re saying “redirect stream 2, stderr, to the same destination that stream 1, stdout, is being redirected to.”

      2>&1 :这使用&>重定向指令。 该指令允许您告诉Shell使一个流与另一流到达相同的目的地。 在这种情况下,我们说的是“将流2 stderr重定向到与流1 stdout重定向到的相同目的地”。

    ./error.sh > capture.txt 2&>1 in a terminal window

    There is no visible output. That’s encouraging.

    没有可见的输出。 令人鼓舞。

    output of ./error.sh in a terminal window

    Let’s check the capture.txt file and see what’s in it.

    让我们检查capture.txt文件并查看其中的内容。

    cat capture.txt
    
    contents of capture.txt in a terminal window

    Both the stdout and stderr streams have been redirected to a single destination file.

    stdoutstderr流都已重定向到单个目标文件。

    To have the output of a stream redirected and silently thrown away, direct the output to /dev/null.

    要重定向并静默丢弃流的输出,请将输出定向到/dev/null

    在脚本中检测重定向 (Detecting Redirection Within a Script)

    We discussed how a command can detect if any of the streams are being redirected, and can choose to alter its behavior accordingly. Can we accomplish this in our own scripts? Yes, we can. And it is a very easy technique to understand and employ.

    我们讨论了命令如何检测是否有任何流被重定向,并可以选择相应地更改其行为。 我们可以在自己的脚本中完成此操作吗? 我们可以。 这是一种非常容易理解和使用的技术。

    Type the following text into an editor and save it as input.sh.

    在编辑器中键入以下文本,并将其另存为input.sh。

    #!/bin/bash
    
    if [ -t 0 ]; then
    
      echo stdin coming from keyboard
     
    else
    
      echo stdin coming from a pipe or a file
     
    fi
    

    Use the following command to make it executable:

    使用以下命令使其可执行:

    chmod +x input.sh
    

    The clever part is the test within the square brackets. The -t (terminal) option returns true (0) if the file associated with the file descriptor terminates in the terminal window. We’ve used the file descriptor 0 as the argument to the test, which represents  stdin.

    聪明的部分是方括号内的测试 。 如果与文件描述符关联的文件在终端窗口中终止,则 -t (terminal)选项返回true(0)。 我们使用文件描述符0作为测试的参数,它表示stdin

    If stdin is connected to a terminal window the test will prove true. If stdin is connected to a file or a pipe, the test will fail.

    如果将stdin连接到终端窗口,则测试将证明是正确的。 如果stdin连接到文件或管道,则测试将失败。

    We can use any convenient text file to generate input to the script. Here we’re using one called dummy.txt.

    我们可以使用任何方便的文本文件来生成脚本的输入。 在这里,我们使用一个叫做dummy.txt的文件。

    ./input.sh < dummy.txt
    
    ./input.sh < dummy.txt in a terminal window

    The output shows that the script recognizes that the input isn’t coming from a keyboard, it is coming from a file. If you chose to, you could vary your script’s behavior accordingly.

    输出显示该脚本识别出输入不是来自键盘,而是来自文件。 如果选择这样做,则可以相应地更改脚本的行为。

    output from script in a terminal window

    That was with a file redirection, let’s try it with a pipe.

    那是与文件重定向有关的,让我们通过管道进行尝试。

    cat dummy.txt | ./input.sh
    
    cat dummy.txt | ./input.sh in a terminal window

    The script recognizes that its input is being piped into it. Or more precisely, it recognizes once more that the stdin stream is not connected to a terminal window.

    该脚本识别出其输入正在通过管道传递到其中。 或更准确地说,它再次识别出stdin流未连接到终端窗口。

    output of script in a terminal window

    Let’s run the script with neither pipes nor redirects.

    让我们既不使用管道也不使用重定向来运行脚本。

    ./input.sh
    
    ./input.sh in a terminal window

    The stdin stream is connected to the terminal window, and the script reports this accordingly.

    stdin流已连接到终端窗口,脚本相应地对此进行报告。

    To check the same thing with the output stream, we need a new script. Type the following into an editor and save it as output.sh.

    要在输出流中检查同一件事,我们需要一个新脚本。 在编辑器中键入以下内容,并将其另存为output.sh。

    #!/bin/bash
    
    if [ -t 1 ]; then
    
    echo stdout is going to the terminal window
     
    else
    
    echo stdout is being redirected or piped
     
    fi
    

    Use the following command to make it executable:

    使用以下命令使其可执行:

    chmod +x input.sh
    

    The only significant change to this script is in the test in the square brackets. We’re using the digit 1 to represent the file descriptor for stdout.

    对该脚本的唯一重大更改是在方括号中的测试中。 我们使用数字1表示stdout文件描述符。

    Let’s try it out. We’ll pipe the output through cat.

    让我们尝试一下。 我们将通过cat传递输出。

    ./output | cat
    
    ./output | cat in a terminal window

    The script recognizes that its output is no going directly to a terminal window.

    该脚本识别出其输出不会直接进入终端窗口。

    script output in a terminal window

    We can also test the script by redirecting the output to a file.

    我们还可以通过将输出重定向到文件来测试脚本。

    ./output.sh > capture.txt
    
    ./output.sh > capture.txt in a terminal window

    There is no output to the terminal window, we are silently returned to the command prompt. As we’d expect.

    没有输出到终端窗口,我们默默地返回到命令提示符。 正如我们所期望的。

    script output in a terminal window

    We can look inside the capture.txt file to see what was captured. Use the following command to do so.

    我们可以查看capture.txt文件内部,以查看捕获的内容。 使用以下命令进行操作。

    cat capture.sh
    
    cat capture.sh in a terminal window

    Again, the simple test in our script detects that the stdout stream is not being sent directly to a terminal window.

    再次,脚本中的简单测试检测到stdout流没有直接发送到终端窗口。

    If we run the script without any pipes or redirections, it should detect that stdout is being delivered directly to the terminal window.

    如果我们运行脚本时没有任何管道或重定向,它应该检测到stdout是否直接传递到终端窗口。

    ./output.sh
    
    ./output.sh in a terminal window

    And that’s exactly what we see.

    这就是我们所看到的。

    script output in a terminal window

    意识流 (Streams Of Consciousness)

    Knowing how to tell if your scripts are connected to the terminal window, or a pipe, or are being redirected, allows you to adjust their behavior accordingly.

    知道如何判断脚本是连接到终端窗口还是管道,还是正在重定向,可以使您相应地调整其行为。

    Logging and diagnostic output can be more or less detailed, depending on whether it is going to the screen or to a file. Error messages can be logged to a different file than the normal program output.

    日志和诊断输出的详细程度可能有所不同,具体取决于它是进入屏幕还是进入文件。 错误消息可以记录到与普通程序输出不同的文件中。

    As is usually the case, more knowledge brings more options.

    通常,更多的知识带来更多的选择。

    翻译自: https://www.howtogeek.com/435903/what-are-stdin-stdout-and-stderr-on-linux/

    展开全文
  • 这提供了bundle-update_stdout update_stdout ,这不是实际的更新,但是可以很容易地与旧版本进行比较! 安装 将此行添加到应用程序的Gemfile中: gem 'bundler-update_stdout' 然后执行: $ bundle 或将其自己...
  • <pre><code>$stdout = fopen ("/dev/stdout","w"); fwrite($stdout, "fails"); $stderr = fopen ("/dev/stderr","w"); fwrite($stderr, "fails"); echo "fd1 exists:" . (file_exists('/proc/self/fd/1') ? 'yes' :...
  • <p>For some reason <code>os.Stdout = new_stdout</code> doesn't want to work. I'm fairly certain this should be an allowed assignment as I use something of similar structure in my FUSE file system, so ...
  • nodejs process stdout

    2021-10-05 14:27:44
    setInterval(function () { process.stdout.clearLine() process.stdout.moveCursor(-13, 0) process.stdout.write(`${new Date().getTime()}`) }, 100)
    
    setInterval(function () {
        process.stdout.clearLine()
        process.stdout.moveCursor(-13, 0)
        process.stdout.write(`${new Date().getTime()}`)
    }, 100)

    展开全文
  • stderr和stdout详细解说

    千次阅读 2019-04-09 21:04:18
    <cstdio> object stderr FILE * stderr; ...Standard error stream ...The standard error stream is the defaultdestination for error messages and other diagnostic warnings... Like stdout, itis usually a...
  • 此模块允许运行“原始”终端命令,并将其输出输出到stdout和stderr。 命令不会按时间顺序运行,每个命令只能在每个SM上运行一次。 例子 作为options , raw-module SMF接受要执行的命令数组( string[] ): ...
  • 在定位一个 dpdk 程序 ifconfig up 接口异常问题时,由于程序是由后台拉起的,stdout 被重定位为 /dev/null 无法获取到错误信息,并且我不能杀掉程序(这可能会破坏现场),故而需要改变运行程序的 stdout。...
  • <p>Setting the non-block flag through <code>unix.SetNonblock</code> on stdout file descriptor seems to solve the above issue but you can't know prior if it's ready or not and an error saying "resource...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 437,865
精华内容 175,146
关键字:

stdout