简体   繁体   中英

Retrieve yum repos and save as list in json format

I am new to the site and have just started with Python. I am trying to think how to begin working on this problem...basically I need Python to retrieve a list of all yum repos in /etc/yum.repos.d and then save the list in a json format such as below:

{
    "[repo_name]" : {
        "name" : "repo_name",
        "baseurl" : "http://example.com",
        "enabled" : "1",
        "gpgcheck" : "0"
    }
    "[next_repo]...
}

I managed to get something working, but it doesn't really do what it was intended to do. Here is the code I have:

#!/usr/bin/python

import json

mylist = []
lines = open('/etc/yum.repos.d/repo_name.repo').read().split('\n')

for line in lines:
    if line.strip() != '':
            if '[' in line:
                    mylist.append("{")
                    repo_name = line.translate(None,'[]')
                    mylist.append(repo_name + ':')
                    mylist.append("{")

            elif 'gpgcheck' in line:
                    left, right = line.split('=')
                    mylist.append(left + ':' + right)
                    mylist.append("}")
            else:
                    left, right = line.split('=')
                    mylist.append(left + ':' + right)

out_file = open('test.json','w')
out_file.write(json.dumps(mylist))
out_file.close()

And here is what it returns:

["{", "repo_name:", "{", "name:repo_name", "baseurl:http://www.example.com", "enabled:1", "gpgcheck:0", "}"]

I haven't coded in for multiple repos yet, since I just wanted to get one working first. Am I approaching this correctly or is there a better way? OS is RHEL and python version is 2.6.6. Any help is greatly appreciated!

This a example file structure

[examplerepo]
name=Example Repository
baseurl=http://mirror.cisp.com/CentOS/6/os/i386/
enabled=1
gpgcheck=1
gpgkey=http://mirror.cisp.com/CentOS/6/os/i386/RPM-GPG-KEY-CentOS-6

And this is a code I used

#!/usr/bin/python

import json

test_dict = dict()
lines = open('test', 'r').read().split('\n')
current_repo = None

for line in lines:
    if line.strip() != '':
            if '[' in line:
                current_repo = line
                test_dict[current_repo] = dict()
            else:
                k, v = line.split("=")
                test_dict[current_repo][k] = v

out_file = open('test.json', 'w')
out_file.write(json.dumps(test_dict))
out_file.close()

I think that using dictionaries is more natural way to do this.

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