Re: Linux shell to python

Discussion in 'Python' started by Peter Otten, Jul 30, 2012.

  1. Peter Otten

    Peter Otten Guest

    Vikas Kumar Choudhary wrote:


    > let me know if someone has tried to implement (grep and PIPE) shell
    > commands in python `lspci | grep Q | grep "$isp_str1" | grep "$isp_str2"
    > | cut -c1-7'
    >
    > I tried to use python subprocess and OS.Popen modules.


    subprocess is the way to go.

    > I was trying porting from bash shell to python.


    Here's an example showing how to translate a shell pipe:

    http://docs.python.org/library/subprocess.html#replacing-shell-pipeline

    But even if you can port the shell script literally I recommend a more
    structured approach:

    import subprocess
    import itertools

    def parse_data(lines):
    for not_empty, group in itertools.groupby(lines, key=bool):
    if not_empty:
    triples = (line.partition(":") for line in group)
    pairs = ((left, right.strip()) for left, sep, right in triples)
    yield dict(pairs)

    if __name__ == "__main__":
    def get(field):
    return entry.get(field, "").lower()
    output = subprocess.Popen(["lspci", "-vmm"],
    stdout=subprocess.PIPE).communicate()[0]
    for entry in parse_data(output.splitlines()):
    if "nvidia" in get("Vendor") and "usb" in get("Device"):
    print entry["Slot"]
    print entry["Device"]
    print
     
    Peter Otten, Jul 30, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    2
    Views:
    5,898
    Jonathan Bromley
    Feb 18, 2005
  2. Christian Heimes
    Replies:
    0
    Views:
    631
    Christian Heimes
    Feb 27, 2008
  3. Gerardo Herzig
    Replies:
    1
    Views:
    1,145
    Philipp Pagel
    Feb 27, 2008
  4. D'Arcy J.M. Cain
    Replies:
    0
    Views:
    893
    D'Arcy J.M. Cain
    Feb 27, 2008
  5. edwithad

    Bash shell to Python shell?

    edwithad, Sep 28, 2009, in forum: Python
    Replies:
    4
    Views:
    1,811
Loading...

Share This Page