[英]Retrieve yum repos and save as list in json format
I am new to the site and have just started with Python. 我是该网站的新手,并且刚开始使用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:
我试图思考如何开始解决这个问题...基本上我需要Python在/etc/yum.repos.d中检索所有yum存储库的列表,然后将列表以json格式保存,如下所示:
{
"[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.
操作系统是RHEL,python版本是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. 我认为使用字典是更自然的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.