lost and found ( for me ? )

Python : execute Linux commands in python by using popen2 or subprocess

small tips.
Here’s an example of how to use popne2 / subprocess .


# python --version
Python 2.7.3


[ use popne2 ]

nnn , the output includes empty lines..
# python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import popen2
>>> cmd1 = 'ls -a'
>>> stdout_cmd1,stdin_cmd1,stderr_cmd1 = popen2.popen3(cmd1)
>>> for i in stdout_cmd1.readlines():
...     print i
...
.

..

.ICEauthority
    <- empty line
.Xauthority
    <- empty line
.Xmodmap

.aptitude

.bash_history

.cache

.config
<snip>
>>>


to remove empty lines , use rstrip() method.
>>> stdout_cmd1,stdin_cmd1,stderr_cmd1 = popen2.popen3(cmd1)
>>> for i in stdout_cmd1.readlines():
...     print i.rstrip()
...
.
..
.ICEauthority
.Xauthority
.Xmodmap
.aptitude
.bash_history
.cache
.config
.dbus
.gconf
.gnome2
.gns3
.gstreamer-0.10
.gtk-bookmarks
.guestfish
.gvfs
.john
.lesshst
.linuxmint
.local
.mateconf
.mateconfd
.mbrowse
.mbrowse_bookmarks
.msf4
.pki
.profile
.pulse
.pulse-cookie
.rnd
.scapy_history
.selected_editor
.spicec
.ssh
.synaptic
.toprc
.virsh
.virt-manager
.virtinst
.vnc
.w3af
.xsession-errors
Desktop
Documents
Downloads
Music
Pictures
Public
Templates
Videos


[ use subprocess ]
# python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> cms1 = 'ls -a'
>>> for i in result_cmd1.stdout.readlines():
...     print i.rstrip()
...
.
..
.ICEauthority
.Xauthority
.Xmodmap
.aptitude
.bash_history
.cache
.config
.dbus
.gconf
.gnome2
.gns3
.gstreamer-0.10
.gtk-bookmarks
.guestfish
.gvfs
.john
.lesshst
.linuxmint
.local
.mateconf
.mateconfd
.mbrowse
.mbrowse_bookmarks
.msf4
.pki
.profile
.pulse
.pulse-cookie
.rnd
.scapy_history
.selected_editor
.spicec
.ssh
.synaptic
.toprc
.virsh
.virt-manager
.virtinst
.vnc
.w3af
.xsession-errors
Desktop
Documents
Downloads
Music
Pictures
Public
Templates
Videos
>>>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.