是的,正如我在对我的问题的评论中提到的,sqlite3 听起来很有希望......当我学会阅读的那一天,我将征服世界!
无论如何,以防万一对其他人有帮助:
#!/usr/bin/env python
import os
import sqlite3
import pwd
_cookieName = "preferredLanguage"
def getPreferredLanguageFromCookieDB():
retval="en-US"
cookieDBFilename = os.path.join(pwd.getpwuid(1000).pw_dir, ".config/google-chrome/Default/Cookies")
if os.path.isfile(cookieDBFilename):
connection = sqlite3.connect(cookieDBFilename)
querier = connection.cursor()
numCookiesMatching = int(querier.execute('SELECT COUNT(*) FROM cookies WHERE (host_key="127.0.0.1" or host_key="localhost") and name="%s"' % (_cookieName)).fetchone()[0])
if numCookiesMatching == 1:
retval = querier.execute('SELECT value FROM cookies WHERE (`cookies`.`host_key`="127.0.0.1" or `cookies`.`host_key`="localhost") and `cookies`.`name` = "%s"' % (_cookieName)).fetchone()[0]
elif numCookiesMatching == 0:
print("::getPreferredLanguageFromCookieDB > No cookie for '%s' found. Assuming wizard hasn't run yet, which is weird, but not critical" % (_cookieName))
retval="en-US"
else:
raise KeyError("Found %s cookies matching %s in file %s. This shouldn't have happened" % (numCookiesMatching, _cookieName, cookieDBFilename))
retval=None
else:
print("::getPreferredLanguageFromCookieDB > Cookie 'db' (actually, file) %s doesn't exist" % (cookieDBFilename))
retval="en-US"
return retval
if __name__ == "__main__":
print "Prefered language: %s" % getPreferredLanguageFromCookieDB()
这个小片段将连接到 Cookies“数据库”(实际上只是文件,但无论如何......)并读取由或preferredLanguage
发出的“” cookie的值。如果localhost 发出多个 " " cookie,它将崩溃。localhost
127.0.0.1
preferredLanguage