2

I want to do something easy, but I don't catch... I did many search on Google and I didn't find something!

I'm doing this:

from subprocess import Popen, PIPE

p1 = Popen(["fping", '-C10', '-B1', '-p500',
'-r1', '-s', '172.29.172.106'], stdout=PIPE)
output = p1.communicate()

So, python executes my command, communicate waits the return code, it works fine. But, I don't know why it displays the output... Like this :

172.29.172.106 : 13.50 18.56 13.22 13.42 13.39 187.62 13.34 13.51 13.36 26.35

       1 targets
       1 alive
       0 unreachable
       0 unknown addresses

       0 timeouts (waiting for response)
      10 ICMP Echos sent
      10 ICMP Echo Replies received
       0 other ICMP received

 13.2 ms (min round trip time)
 32.6 ms (avg round trip time)
 187 ms (max round trip time)
        4.530 sec (elapsed real time)

I just want to execute a command then redirect the output to a variable but I don't want to display the output because it floods my crontab log file!

So the question : how to use popen (or other function) to execute a command and redirect output to a variable without display it?

Best regards,

Vender Aeloth
  • 690
  • 1
  • 12
  • 27
  • If you run the command from the CLI, redirecting the output using `> dump.txt`, does it still display in the window? – Alex Chamberlain Oct 16 '14 at 08:31
  • It's a sub-part of my main script. My main script is already using ">> mycrontab.log 2>&1". That's why it's problem... It floods my log file – Vender Aeloth Oct 16 '14 at 08:34

1 Answers1

2
import subprocess 
p1 = Popen(["fping", '-C10', '-B1', '-p500','-r1', '-s', '172.29.172.106'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output,error = p1.communicate()

Try this.

vks
  • 67,027
  • 10
  • 91
  • 124
  • @VenderAeloth the ouput still comes on stdout?can you try and run the edite done? – vks Oct 16 '14 at 09:02
  • user@host:/dir# python test.py 172.29.172.106 : 159.00 13.36 13.55 38.89 161.32 13.19 13.25 44.43 164.31 13.29 1 targets 1 alive 0 unreachable 0 unknown addresses 0 timeouts (waiting for response) 10 ICMP Echos sent 10 ICMP Echo Replies received 0 other ICMP received 13.1 ms (min round trip time) 63.4 ms (avg round trip time) 164 ms (max round trip time) 4.518 sec (elapsed real time) user@host:/dir# As I said the behavior is equal. – Vender Aeloth Oct 16 '14 at 09:07
  • It works... stderr=subprocess.PIPE needed! Don't know why... But it works! Thank you :-) – Vender Aeloth Oct 16 '14 at 09:17
  • 2
    @VenderAeloth you were redirecting your stdout but when the command fails and there is an error ,it goes to `stderr`.So you need to redirect it as well. :) by default stderr goes to output as well. – vks Oct 16 '14 at 09:18