Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

redirect - Suppress output in Python calls to executables

I have a binary named A that generates output when called. If I call it from a Bash shell, most of the output is suppressed by A > /dev/null. All of the output is suppressed by A &> /dev/null

I have a python script named B that needs to call A. I want to be able to generate output from B, while suppressing all the output from A.

From within B, I've tried os.system('A'), os.system('A > /dev/null'), and os.system('A &> /dev/null'), os.execvp('...'), etc. but none of those suppress all the output from A.

I could run B &> /dev/null, but that suppresses all of B's output too and I don't want that.

Anyone have suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import os
import subprocess

command = ["executable", "argument_1", "argument_2"]

with open(os.devnull, "w") as fnull:
    result = subprocess.call(command, stdout = fnull, stderr = fnull)

If the command doesn't have any arguments, you can just provide it as a simple string.

If your command relies on shell features like wildcards, pipes, or environment variables, you'll need to provide the whole command as a string, and also specify shell = True. This should be avoided, though, since it represents a security hazard if the contents of the string aren't carefully validated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...