简体   繁体   English

如何在jupyter中抑制来自sys和os的消息?

[英]How to suppress messages from sys and os in jupyter?

My question is similar to a bunch of other questions on this forum, but none of the solutions seem to work.我的问题与该论坛上的许多其他问题类似,但似乎没有一个解决方案有效。 I have a function which calls a command line function which print some stuff.我有一个 function 调用命令行 function 打印一些东西。 I want this stuff not printed in my notebook.我希望这些东西不要印在我的笔记本上。 However, for the sake of reproducing let us use the function:但是,为了重现,让我们使用 function:

import os

def p():
    os.system('echo some_stuff')

If this function is executed in a jupyter cell, then %%capture or any of the other proposed solutions doesn't suppress it.如果此 function 在 jupyter 单元中执行,则%%capture或任何其他建议的解决方案都不会抑制它。

Secondly, &> /dev/null is not an option for my purposes.其次, &> /dev/null不是我的选择。

Using os.system doesn't let you control anything with the process, so it'll inherit the stdout handle and print to it directly, with your Python process not being able to do anything about it.使用os.system不会让您控制该进程的任何内容,因此它将继承 stdout 句柄并直接打印到它,而您的 Python 进程无法对其执行任何操作。

You should use subprocess which lets you control the child process' creation more, along with being able to view its output etc. if necessary.您应该使用子进程来控制子进程的创建,并在必要时查看其 output 等。 In this case you could redirect the standard streams to devnull, or if you need to interact with it using subprocess.PIPE .在这种情况下,您可以将标准流重定向到 devnull,或者如果您需要使用subprocess.PIPE与之交互。

As an additional bonus, subprocess doesn't run in the shell by default (although it can with the shell=True specified) which will be a tad faster and could be safer.作为额外的奖励,默认情况下,子进程不会在 shell 中运行(尽管它可以使用shell=True指定),这会更快一些并且可能更安全。

For example here the first process prints to stdout as it's not redirected anywhere, the second process' output is suppressed, and the third process' output is captured and accessible through the stdout attribute on the returned CompletedProcess object.例如,这里第一个进程打印到标准输出,因为它没有被重定向到任何地方,第二个进程的 output 被抑制,第三个进程的 output 被捕获并通过返回的 CompletedProcess ZA8CFDE6331BD4FB666AC1 上的stdout属性访问。

In [90]: subprocess.run(["python", "-c", "print('printed')"])
printed
Out[90]: CompletedProcess(args=['python', '-c', "print('printed')"], returncode=0)

In [91]: subprocess.run(
    ...:     ["python", "-c", "print('printed')"],
    ...:     stdout=subprocess.DEVNULL,
    ...:     stderr=subprocess.DEVNULL,
    ...: )
Out[91]: CompletedProcess(args=['python', '-c', "print('printed')"], returncode=0)

In [92]: subprocess.run(
    ...:     ["python", "-c", "print('printed')"],
    ...:     stdout=subprocess.PIPE,
    ...:     stderr=subprocess.PIPE,
    ...: )
Out[92]: CompletedProcess(args=['python', '-c', "print('printed')"], returncode=0, stdout=b'printed\r\n', stderr=b'')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM