...
Just my blog

Blog about everything, mostly about tech stuff I made. Here is the list of stuff I'm using at my blog. Feel free to ask me about implementations.

Soft I recommend
Py lib I recommend

I'm using these libraries so you can ask me about them.

Python Run External Command And Get Output On Screen or In Variable

Отседова: http://www.cyberciti.biz/faq/python-run-external-command-and-get-output/ The basic syntax is:

import subprocess
subprocess.call("command-name-here")
subprocess.call(["/path/to/command", "arg1", "-arg2"])

Run ping command to send ICMP ECHO_REQUEST packets to www.cyberciti.biz:

#!/usr/bin/python
import subprocess
subprocess.call(["ping", "-c 2", "www.cyberciti.biz"])

Свой вариант:

C:\Python34>python.exe
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call(["ping", "-t", "8.8.8.8"])

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=49ms TTL=43
Reply from 8.8.8.8: bytes=32 time=42ms TTL=43
Reply from 8.8.8.8: bytes=32 time=42ms TTL=43
Reply from 8.8.8.8: bytes=32 time=42ms TTL=43
Reply from 8.8.8.8: bytes=32 time=43ms TTL=43
Reply from 8.8.8.8: bytes=32 time=42ms TTL=43
Reply from 8.8.8.8: bytes=32 time=42ms TTL=43
Reply from 8.8.8.8: bytes=32 time=42ms TTL=43

Ping statistics for 8.8.8.8:
    Packets: Sent = 8, Received = 8, Lost = 0 (0% loss),

Чисто чтобы не забыть, себе шпора. Быть может очень скоро пригодится. С аутпутами пока не разбирался, как-то лениво, начну делать тулзень для автоматизации работы - разберусь по пути!

How do I get real time output from my commands on screen?

The p.communicate() has a few problems:

  1. The data read is buffered in memory, so do not use this method if the data size is large or unlimited.
  2. It will block next statement till external command is completed i.e. you will not get real time output from the command.

The following program will run netstat unix command and start display output immediately on screen:

#!/usr/bin/python
import subprocess
## command to run - tcp only ##
cmd = "/usr/sbin/netstat -p tcp -f inet"
 
## run it ##
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
 
## But do not wait till netstat finish, start displaying output immediately ##
while True:
    out = p.stderr.read(1)
    if out == '' and p.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()