analitics

Pages

Showing posts with label subprocess. Show all posts
Showing posts with label subprocess. Show all posts

Monday, October 7, 2019

Python 3.7.4 : Example with subprocess - part 001.

This is a simple example with the python 3 subprocess package.
The source code is simple to understand.
The execute_proceess_with_communicate let run the ls command with the sudo user permissions:
import os
import sys
import string
import subprocess
import codecs

inp = ''
cmd = 'ls'
password = ''

def execute_proceess_with_communicate(inp):
    """Return a list of hops from traceroute command."""
    p = subprocess.Popen(
            ['sudo', cmd, inp],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            shell=False)
    text, _ = p.communicate(password)
    #print(type(text))
    outp = codecs.decode(text,'utf8')
    out_split=outp.split('\n')
    return out_split

def normalize_out(list_outp):
    """Extract information from traceroute line per line."""

    normalized_out = []
    for op in list_outp:
        # filer out if an empty line
        if len(op) is 0:
            continue
        op_split = op.split()
        normalized_out.append(op_split)
    return normalized_out

if __name__ == '__main__':
    inp = sys.argv[1]

    out = execute_proceess_with_communicate(inp)
    n_out = normalize_out(out)
    print(n_out)
The result is this:
[mythcat@desk scripts]$ python3 subprocess_001.py '/' 
[['bin'], ['boot'], ['dev'], ['etc'], ['home'], ['lib'], ['lib64'], ['media'], ['mnt'], ['opt'], ['proc'],
 ['root'], ['run'], ['sbin'], ['srv'], ['sys'], ['tmp'], ['usr'], ['var']]

Friday, September 1, 2017

The beauty of Python: subprocess module - part 004 .

This series of python tutorials that we started at the beginning of this blog and called "The beauty of Python" is part of the series of tutorials aimed at the simplicity and beauty of the Python programming language.
The main goal for us is how to use this programming language in everyday life with different tasks.
Today I will come up with examples to cover this goal and show you how to use the subprocess python module.
  • using the PowerShell with python :
  • >>> import subprocess
    >>> process=subprocess.Popen(["powershell","Get-Childitem C:\\Windows\\*.log"],stdout=subprocess.PIPE);
    >>> result=process.communicate()[0]
    >>> print result
  • get and print the hostname :
  • >>> print subprocess.check_output("hostname")
  • print the output of ping command :
  • >>> print subprocess.check_output("ping localhost", shell=True)
  • print the output of dir command :
  • >>> cmd = 'dir *'
    >>> supcmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    >>> print supcmd.communicate()[0]
    
  • run the python script like python shell :
  • >>> import sys
    >>> import subprocess
    >>> pid = subprocess.Popen([sys.executable, "calc.py"])

Sunday, September 22, 2013

Check system , distro and commands using python scripts .

This is a simple example with two functions.

First will check the linux command : ls linux command.

The next function will give us some infos about system.

import shlex 
import subprocess
from subprocess import Popen, PIPE

import platform

def check_command(command):
    cmd='which ' + command 
    output = Popen(shlex.split(cmd), stdout=PIPE).communicate()[0]
    command_path =output.split('\n')[0]
    print command_path
    return command_path

def check_platform():
    arch, exe = platform.architecture()
    my_system = platform.system()
    if my_system == 'Linux':
        distro_name, distro_version, distro_id = platform.linux_distribution()
    elif my_system == 'Darwin':
        distro_name, distro_version, distro_id = platform.mac_ver()
    elif my_system == 'Windows':
 distro_name, distro_version, distro_id = platform.win32_ver()
    elif my_system == 'Java':
 distro_name, distro_version, distro_id = platform.java_ver()
    processor = platform.processor() or 'i386'
    print processor, my_system, arch, distro_name, distro_version, distro_id
    return processor, my_system, arch, distro_name, distro_version, distro_id

check_command('ls')

check_platform()

This python script can be use with any scripts when we need to test commands and system , distro version.

Saturday, May 22, 2010

The beauty of Python: subprocess module - part 3

This is just a simple example about module subprocess.
We need to install "espeak" . On fedora usse this command:
#yum install espeak

Now the example is:

>>> import subprocess   
>>> subprocess.call(["espeak", "-s 120","-p 100","This is a test"])
0
>>>   

This will speak "This is a test".
This is all .