按钮正在工作,但线程根本不起作用。是什么导致它失败?
thread.start_new_thread(task1)
语句未执行。
/var/tmp/p.py:
import sys,os
import pygtk, gtk, gobject
import socket, datetime, threading
import ConfigParser
import urllib2
import subprocess
import threading
import thread
# Singleton run once
import fcntl, sys
pid_file = '/var/tmp/program.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
# another instance is running
sys.exit(0)
# Read config file
server="http://blabla"
username="stackoverflow"
password="freak"
language="EN"
# Disconnect
get_disconnect="/a/disconnectusername?username=%s&password=%s&language=%s" % (username,password,language)
disconnect_url="%s%s" % (server,get_disconnect)
# Do multi-thread without blocking the main front-end
def task1():
urllib2.urlopen(disconnect_url)
class GTK_Main:
def __init__(self):
# main GTK
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_size_request(1280, 720)
self.window.set_border_width(10)
self.window.set_decorated(False)
self.window.set_title("Test")
self.window.move(0,0)
self.window.connect("destroy", gtk.main_quit, "WM destroy")
hbox = gtk.HBox(False, 0)
self.vbox.pack_start(hbox, False)
hbox.set_border_width(10)
hbox.pack_start(gtk.Label(), True, True, 0)
# Disconnect
self.button_disconnect = gtk.Button()
self.button_disconnect.set_name("disconnectButton")
self.button_disconnect.connect("clicked", self.disconnectButton)
hbox.pack_start(self.button_disconnect, False)
hbox.add(gtk.Label())
self.window.show_all()
self.window.set_keep_above(True)
if(self.window.get_window().get_state() == gtk.gdk.WINDOW_STATE_MAXIMIZED):
print "unmaximize"
self.window.unmaximize()
def disconnectButton(self, w):
print "Window Resize"
#subprocess.call("java -cp /var/tmp/dist/Audio.jar ui.Connecting1 wait..", shell=True)
#urllib2.urlopen(disconnect_url)
try:
#t1 = threading.Thread(target=task1)
#t1.start()
thread.start_new_thread(task1)
except:
print "Error: threading.."
subprocess.call("/var/tmp/runme.sh", shell=True)
try:
GTK_Main()
gtk.gdk.threads_init()
gtk.main()
except (SystemExit, KeyboardInterrupt):
sock.close()
gtk.main_quit()
/var/tmp/runme.sh:
#!/bin/bash
export DISPLAY=:0.0
# kill please
ps aux | grep p.py | awk '{print $2}' | xargs kill -9;
sleep 2
# kill please
ps aux | grep p.py | awk '{print $2}' | xargs kill -9;
sleep 2
# kill for sure please
ps aux | grep p.py | awk '{print $2}' | xargs kill -9;
# cross finger and run now
python /var/tmp/p.py &
答案 0 :(得分:0)
这是因为
1)你正在运行多线程来抓取网页链接,但是我们链接会花一些时间来提交数据包,有一段时间需要等待......
2)你立即杀死python并重新启动它,结果它杀死了线程,表示它无法正常工作
3)解决此类问题使用
t1 = threading.Thread(target=task1)
t1.start()
t1.join() # this tells to wait until job is done (url crawl)
#thread.start_new_thread(task1)