1

I am currently writing a wrapper for a small console program I wrote.
The c program needs a password string as input and because I intend to use it through dmenu and such, I'd like to use a little gtk entry box to enter that string.
However, I have to fork after I get the input (because I'm also handling clipboard stuff which needs deletion after some time) and the window simply won't close until the child process exits.

from subprocess import Popen, PIPE
from gi.repository import Gtk
import sys
import os
import time
import getpass

HELP_MSG = "foobar [options] <profile>"

class EntryDialog(Gtk.Dialog):

    def run(self):
        result = super(EntryDialog, self).run()
        if result == Gtk.ResponseType.OK:
            text = self.entry.get_text()
        else:
            text = None
        return text

    def __init__(self):
        super(EntryDialog, self).__init__()
        entry = Gtk.Entry()
        entry.set_visibility(False)
        entry.connect("activate", 
                      lambda ent, dlg, resp: 
                          dlg.response(resp), 
                          self, 
                          Gtk.ResponseType.OK)
        self.vbox.pack_end(entry, True, True, 0)
        self.vbox.show_all()
        self.entry = entry

def get_pwd():
    if sys.stdin.isatty():
        return getpass.getpass()
    else:
        prompt = EntryDialog()
        prompt.connect("destroy", Gtk.main_quit)
        passwd = prompt.run()
        prompt.destroy()
        return passwd 

The thought is, that it should close when I hit enter, but I'm pretty sure I'm doing something entirely wrong. The script basically continues like this:

profile = argv[0]
pwd = get_pwd()

if pwd is None:
    print(HELP_MSG)
    sys.exit()

out = doStuff()
text_to_clipboard(out)

# now fork and sleep!
if os.fork():
    sys.exit()

time.sleep(10)

clear_clipboard()

sys.exit(0)
4

1 回答 1

0

我放弃了python包装器并直接用c编写了它。但是,对于任何有同样问题的人,(未经测试的)解决方案是添加一个函数

def quit():
    self.emit("destroy")

其中 'self' 是对话框 - 并将其连接到“激活”信号,

entry.connect("activate", quit)

这样对话框小部件就会在用户点击 Return 时立即发出销毁信号,从而调用 Gtk.main_quit。
在 c 中,可以通过指定 GtkEntryBuffer 并调用它来很好地提取内容

gtk_entry_buffer_get_text()

我现在没有找到它,但可能有 pygtk 的等价物可用。

于 2013-08-26T12:41:46.123 回答