Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing system commands in python

Tags:

python

sys

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 :)

like image 842
Lucas Kauffman Avatar asked Jun 23 '26 00:06

Lucas Kauffman


2 Answers

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
like image 62
Santa Avatar answered Jun 25 '26 15:06

Santa


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

like image 25
urschrei Avatar answered Jun 25 '26 15:06

urschrei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!