Python 3.4.3 subprocess.Popen get output of command without piping?

前端 未结 4 1917
无人及你
无人及你 2021-02-06 05:32

I am trying to assign the output of a command to a variable without the command thinking that it is being piped. The reason for this is that the command in question gives unform

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 05:40

    Many programs automatically turn off colour printing codes when they detect they are not connected directly to a terminal. Many programs will have a flag so you can force colour output. You could add this flag to your process call. For example:

    grep "search term" inputfile.txt 
    # prints colour to the terminal in most OSes
    
    grep "search term" inputfile.txt | less
    # output goes to less rather than terminal, so colour is turned off 
    
    grep "search term" inputfile.txt --color | less
    # forces colour output even when not connected to terminal 
    

    Be warned though. The actual colour output is done by the terminal. The terminal interprets special character espace codes and changes the text colour and background color accordingly. Without the terminal to interpret the colour codes you will just see the text in black with these escape codes interspersed throughout.

提交回复
热议问题