Reputation: 75
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. I want this stuff not printed in my notebook. However, for the sake of reproducing let us use the 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.
Secondly, &> /dev/null
is not an option for my purposes.
Upvotes: 0
Views: 252
Reputation: 839
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.
You should use subprocess which lets you control the child process' creation more, along with being able to view its output etc. if necessary. In this case you could redirect the standard streams to devnull, or if you need to interact with it using 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.
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.
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'')
Upvotes: 1