문제

I'm trying to execute a Python program, redirect its output to a file, and compare the contents of that file to an existing one, all in a single shell command. This is what I have, but of course it's not working:

diff `python3 program.py > redirect_file.txt` compare_file.txt

I'm a Linux noob, so any help in pointing me in the right direction would be great.

도움이 되었습니까?

해결책

The diff command allows you to use a - on the command line to use stdin, so try:

python3 program.py | diff - compare_file.txt

다른 팁

Your command

diff `python3 program.py > redirect_file.txt` compare_file.txt

does not work because of incorrect use of backticks. Backticks differ from double quotes just in that their contents is evaluated by shell and replaced by its standard output. Because you redirected the command’s standard output to a file, backticks now evaluate to empty string. Thus your command is equivalent to:

python3 program.py > redirect_file.txt
diff "" compare_file.txt

But you want:

python3 program.py > redirect_file.txt
diff redirect_file.txt compare_file.txt

If the redirect_file.txt is used just for the diff, you can avoid creating it and speed up the process:

python3 program.py | diff - compare_file.txt

This uses pipe (|), which basically connects standard output of the command on the left to standard input of the command on the right. Diff reads standard input when - is given instead of actual file name, which is a pretty common convention among shell utilities.

You could also use Bash-specific syntax

diff <(python3 program.py) compare_file.txt

but this is not as portable and creates a named pipe, which is unnecessary and potential source of trouble.

Try this one:

python3 program.py > redirect_file.txt && diff redirect_file.txt compare_file.txt
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top