3

I have experience with perl for writing scripts, which made it easy for me executing linux commands by using back-ticks. I was wondering, how can I do this Python ? Is there a special way for capturing the result of a command (output) ?

thank you :)

2 Answers 2

6

To add to urschrei's answer, here's an example (Windows):

>>> import subprocess
>>> p = subprocess.Popen(['ping', '192.168.111.198'], stdout=subprocess.PIPE, st
derr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out

Pinging 192.168.111.198 with 32 bytes of data:
Reply from 192.168.111.198: bytes=32 time<1ms TTL=128
Reply from 192.168.111.198: bytes=32 time<1ms TTL=128
Reply from 192.168.111.198: bytes=32 time<1ms TTL=128
Reply from 192.168.111.198: bytes=32 time<1ms TTL=128

Ping statistics for 192.168.111.198:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

>>> print err

>>> print p.returncode
0
Sign up to request clarification or add additional context in comments.

Comments

2

You're looking for the subprocess module, specifically the subprocess.check_call() and/or subprocess.check_output() commands.

1 Comment

For backward-compatibility, you might want to be a bit careful with check_output, which is only on >=2.7. Before 2.7, you probably need to use Popen with subprocess.PIPE

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.