Python线程难度

时间:2013-12-14 01:55:58

标签: python multithreading

我正在制作一个小程序,它会显示加载消息,同时通过ping谷歌检查你是否有互联网功能。但每当我尝试运行它时,它只会停留在小装载小发明上。有什么想法吗?

修改

所以我解决了加载Gizmo没有停止的问题,但现在我有另一个问题。此来源是较大程序的片段,当程序确定您的互联网正常运行时,加载Gizmo将停止。它应该ping一些网站,但它只是等待一秒然后退出。有谁知道这是怎么回事?

import urllib2, time, threading
def ping():
try:
    urllib2.urlopen("http://www.google.com")
    network = 1
except IOError:
    network = 0

def network_waiting():
    while network == '?':
        print "\r[*] Checking network availability.... \ ",
        time.sleep(.07)
        print "\r[*] Checking network availability.... |",
        time.sleep(.07)
        print "\r[*] Checking network availability.... /",
        time.sleep(.07)
        print "\r[*] Checking network availability.... -",
        time.sleep(.07)

thread1 = threading.Thread(target = ping) 
thread2 = threading.Thread(target = network_waiting)

thread1.start()
thread2.start() 

2 个答案:

答案 0 :(得分:2)

关于如何实际定义和启动线程可能存在一些混淆。您不能通过在变量名称中使用“thread”来创建线程。您可以这样做的一种方法是创建一个知道调用ping和network_waiting方法的线程对象。这是一个这样做的例子:

thread1 = threading.Thread(target = ping)
thread2 = threading.Thread(target = network_waiting)
thread1.start()
thread2.start()

如果您对其他教程感兴趣,请查看this tutorial


编辑:现在您已将调用修复为线程,请参阅上面的@vanza注释。以下是将network声明为全局变量的方法(讨论如下):

import urllib2, time, threading
network = '?'
def ping():
  global network
  try:
      urllib2.urlopen("http://www.google.com")
      network = 1
  except IOError:
      network = 0

def network_waiting():
  global network
  while network == '?':
      print "\r[*] Checking network availability.... \ ",
      time.sleep(.07)
      print "\r[*] Checking network availability.... |",
      time.sleep(.07)
      print "\r[*] Checking network availability.... /",
      time.sleep(.07)
      print "\r[*] Checking network availability.... -",
      time.sleep(.07)

thread1 = threading.Thread(target = ping) 
thread2 = threading.Thread(target = network_waiting)

thread1.start()
thread2.start() 

基本上,不使用global关键字,Python认为在ping方法中,您正在创建一个名为network的局部变量并写入它,而不是覆盖{{ 1}}全局范围内的变量。

答案 1 :(得分:0)

print语句打印到默认缓冲的stdout。您可以使用stderr报告进度。另外一个线程就足够了:

#!/usr/bin/env python2
import itertools
import sys
import threading
import time
import urllib2

def is_internet_up():
    try:
        urllib2.urlopen("http://stackoverflow.com", timeout=30).close()
    except EnvironmentError:
        return False
    else:
        return True

def show_spinner(msg):
    def spin():
        for c in itertools.cycle(r"\|/-"):
            if stopped.is_set():
                break
            sys.stderr.write("\r%s %s" % (msg, c))
            time.sleep(0.07)

    stopped = threading.Event()
    thread = threading.Thread(target=spin)
    thread.daemon = True
    thread.start()
    return stopped.set

stop_spinner = show_spinner("[*] Checking network availability....")
isup = is_internet_up()
stop_spinner()
print("\rInternet is " + ("up" if isup else "down"))