gen. python Q: How to process ext. program output? [solved]

Hi.

Sorry to ask this rather off topic question, but: How can I process the output of an external programm I started from within python code?

Scenario:
Up to now I used to use ipac-ng to count the traffic from and to various IPs. Due to the fact that the old distributions shipping ipac-ng are outdated and the program isn’t going to work with newer kernel releases, I am writing my own iptables-script by now. I know that it is easy to let the std-out > file and then read the written file, however, I hope there is an easier way doing this.
I also know that it is an security risk to call an “os” function like that. However, I need IP based traffic over an certain ammount of time. I can’t monitor ports or interfaces because one interface can carry a dozen of IPs.

Currently I am doing it like that:

traffic_cmd="_some_command_stuff_here > /tmp/random_dir/output.txt"
os.system(traffic_cmd)
traffic_output=open("/tmp/random_dir/output.txt","r")
do_something(traffic_output)

Is there no more convenient way to do it? I know that Perl can handle called programs output directly inline. Is there something similar in Python? I mean: I don’t know MUCH about Python. But its beating knowledge about perl many times. :smiley:

(Plus: the given code has no watchdog timer. If the traffic_cmd never ends, the script also never will. :neutral_face: )

Thanks in advance! :mrgreen:

Regards, Bigfoot29

You can use the old “os.popen2/3/4” methods to start an external sub-process and have control over io-pipes, that is read from them or write to them (if you external program also accepts interactive input).

I think these methods are deprecated in Python 2.6, and you can already use the “subprocess” module.

Hi.
That looks promising. Thanks.
Due to the fact that not ALL machines are running 2.6, the popen3 seems to be the best choice for now.

Will give a answer on how its working once its working. :smiley:

Regards, Bigfoot29

Double-Posting… yay! 8)

enn0x: Thanks! I am using popen2.popen4() - works like a charm.

Regards, Bigfoot29