简体   繁体   中英

How to search within an argument and output a certain value

I have the following script and I can't get it to search for a string and then output the value.

How do I take the Argument and Split it up so I can search for "endpoint-machine-name=" and then output its value?

Here is the command:

python -u HostnameScript.py "discover-repository-location=null, Employee Notified=null, Manager     Title=Exec Dir Biostatistics, date-detected=Mon Aug 25 16:03:35 PDT 2014, endpoint-machine-name=Davidpc, incident-id=603, sender-ip=null, Machine Name=null, Assigned To=null, Business Unit=Development US"

I have tried splitting it up, but can't search it correctly.

import sys, socket, string, commands, os, re, subprocess

arguments=sys.argv[1:]

for args in [item.split(", ") for item in arguments[]:
 if item.find("endpoint-machine-name=") != -1
 value=item.strip("endpoint-machine-name=")
 sys.stdout.write('Hostname=');print value

All I end up getting is

Hostname=discover-repository-location=null, Employee Notified=null, Manager Title=Exec Dir Biostatistics, date-detected=Mon Aug 25 16:03:35 PDT 2014, endpoint-machine-name=Davidpc, incident-id=603, sender-ip=null, Machine Name=null, Assigned To=null, Business Unit=Development US

How about something like this?

import sys

pairs = sys.argv[1]

for p in pairs.split(', '):
    if 'endpoint-machine-name=' in p:
        print p.replace('endpoint-machine-name=', 'Hostname=')
        break

...or, if you really want to parse the pairs:

import sys

pairs = sys.argv[1]

for p in pairs.split(', '):
    k, v = p.split('=', 1)

    if k == 'endpoint-machine-name':
        print 'Hostname={0}'.format(v)
        break

Of course, you'll have issues if the string ', ' appears anywhere in your values. Also, strip does not function in that way. strip takes a string as an argument which represents the set of characters which should be stripped from the string, not a specific ordered sequence of characters.

If, as you mention, you need to use the functionality in some other script, make it into a stand-alone function:

import sys

function find_host(pairs):
    for p in pairs.split(', '):
        k, v = p.split('=', 1)

        if k == 'endpoint-machine-name':
            print 'Hostname={0}'.format(v)
            break

if __name__ == '__main__':
    find_host(sys.argv[1])

All thanks for you help.. I figured it out with you help of course.

Here is the code I used.

#!/usr/bin/python

import sys

value2 = sys.argv[1:]


for p in value2:
    if 'policy-name=' in p:
            print p.replace('policy-name=','Policy Name=')
    if 'date-detected=' in p:
            print p.replace('date-detected=','Event Date=')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM