[英]Retrieve yum repos and save as list in json format
我是該網站的新手,並且剛開始使用Python。 我試圖思考如何開始解決這個問題...基本上我需要Python在/etc/yum.repos.d中檢索所有yum存儲庫的列表,然后將列表以json格式保存,如下所示:
{
"[repo_name]" : {
"name" : "repo_name",
"baseurl" : "http://example.com",
"enabled" : "1",
"gpgcheck" : "0"
}
"[next_repo]...
}
我設法使某些東西正常工作,但是它並沒有真正做到預期的目的。 這是我的代碼:
#!/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()
這是它返回的內容:
["{", "repo_name:", "{", "name:repo_name", "baseurl:http://www.example.com", "enabled:1", "gpgcheck:0", "}"]
我還沒有編碼多個存儲庫,因為我只想先使一個工作。 我是正確解決這個問題還是有更好的方法? 操作系統是RHEL,python版本是2.6.6。 任何幫助是極大的贊賞!
這是一個示例文件結構
[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
這是我使用的代碼
#!/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()
我認為使用字典是更自然的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.