简体   繁体   English

在PyQt4中使用KWallet

[英]Using KWallet in PyQt4

如果有人能告诉我如何在pyqt4中使用KWallet,那将会很棒

Tutorial in the Python command line Python命令行中的教程

First I will show how kwallet can be used from the Python command line to read and write a password: 首先,我将展示如何使用Python命令行中的kwallet来读取和写入密码:

$ python

# We import the necessary modules.
>>> from PyKDE4.kdeui import KWallet
>>> from PyQt4 import QtGui

# We create a QApplication. We will not use it, but otherwise
# we would get a "QEventLoop: Cannot be used without
# QApplication" error message.
>>> app = QtGui.QApplication([])

# We open the wallet.
>>> wallet = KWallet.Wallet.openWallet(
                 KWallet.Wallet.LocalWallet(), 0)

# We create a folder in which we will store our password,
# and set it as current.
>>> wallet.createFolder('myfolder')
True
>>> wallet.hasFolder('myfolder')
True
>>> wallet.setFolder('myfolder')
True

# We read the password (which does not exist yet), write it,
# and read it again.
>>> wallet.readPassword('mykey')
(0, PyQt4.QtCore.QString(u''))
>>> wallet.writePassword('mykey', 'mypassword')
0
>>> wallet.readPassword('mykey')
(0, PyQt4.QtCore.QString(u'mypassword'))

Tutorial as a Python module 教程作为Python模块

Usually you want to create some simple functions to wrap around the kwallet methods. 通常你想创建一些简单的函数来包装kwallet方法。 The following Python module can open the wallet, get and set a password: 以下Python模块可以打开钱包,获取并设置密码:

#!/usr/bin/python

from PyKDE4.kdeui import KWallet
from PyQt4 import QtGui

def open_wallet():
    app = QtGui.QApplication([])
    wallet = KWallet.Wallet.openWallet(
                 KWallet.Wallet.LocalWallet(), 0)
    if not wallet.hasFolder('kwallet_example'):
        wallet.createFolder('kwallet_example')
    wallet.setFolder('kwallet_example')
    return wallet

def get_password(wallet):
    key, qstr_password = wallet.readPassword('mykey')

    # converting the password from PyQt4.QtCore.QString to str
    return str(qstr_password)

def set_password(wallet, password):
    wallet.writePassword('mykey', password)

It can be used in the following way: 它可以通过以下方式使用:

$ python
>>> import kwallet_example
>>> wallet = kwallet_example.open_wallet()
>>> kwallet_example.set_password(wallet, 'mypass')
>>> kwallet_example.get_password(wallet)

我在这里找到了一个很好的例子,你还需要使用PyKDE4而不仅仅是PyQt。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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