Python 2.7中的线程问题

时间:2017-06-29 21:30:54

标签: python python-2.7 python-multithreading

import time
import thread
import termios
import sys
import datetime


try:
    from msvcrt import getch  # try to import Windows version
except ImportError:
    def getch():   # define non-Windows version
        import tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

def tm():

    char = None

    def keypress():
        count=0
        while count<5:
            a=time.time()
            global char
            char = getch()
            b=time.time()
            c=b-a       
            c=c*10000000000000000
            c=int (c)       
            c=c%1000            
            print c
            count+=1



    thread.start_new_thread(keypress, ())

    while True:
        '''if char is not None:
            print("Key pressed is " + char.decode('utf-8'))
            break'''
        print("Program is running")
        time.sleep(5)

thread.start_new_thread(tm ())  

当我运行如上所示的代码时,它很乐意完成它的意图,即测量击键之间的时间并在测量中给出3个最低有效数字。

然而,当我拿出这部分时(因为我不需要也不一定想要它):

while True:
        '''if char is not None:
            print("Key pressed is " + char.decode('utf-8'))
            break'''
        print("Program is running")
        time.sleep(5)

它破了。我收到以下错误代码:

Traceback (most recent call last):
  File "randgen.py", line 50, in <module>
    thread.start_new_thread(tm ())
TypeError: start_new_thread expected at least 2 arguments, got 1

更新

当我向thread.start_new_thread(tm, ())添加逗号时,我收到此错误:

Unhandled exception in thread started by sys.excepthook is missing lost sys.stderr 但是,当逗号丢失时,只要那段while True代码存在就可以正常运行。

2 个答案:

答案 0 :(得分:4)

你应该使用threading而不是thread thread模块是启动线程的低级接口,它需要很多不必要的麻烦而你正在学习这个。 See this post

然后,启动线程的正确方法是

import threading
import time

def printstuff(stuff):
    while 1:
        print(stuff)
        time.sleep(3)

t = threading.Thread(target=printstuff, args=('helloworld',))
t.start()

# Here is where your main thread will do whatever
print('Main thread running')
time.sleep(5)
print('Main thread done')

# At this point the main thread will be done
# but printstuff will still be printing stuff. 
# Control-c will exit the second thread, and 
# youll be back at a prompt

上面的代码不是一个最小的例子,很难理解你实际想要完成的事情。尝试在一些伪代码中澄清目标,然后我可以与您合作以提高您对多线程的理解。

答案 1 :(得分:2)

单独的线程

如果你真的打算在一个单独的线程中运行tm,那么你在两个位置参数之间缺少一个逗号。它应如下所示:

thread.start_new_thread(tm, ())

主线程

如果你不需要在另一个线程中执行tm,那么简单地调用当前线程中的函数就像这样:

tm()

由于Python解释器删除了空格,所以这已经没有了逗号。

thread.start_new_thread(tm ())
# gets turned into
thread.start_new_thread(tm())
# which evaluates tm() before calling 'start_new_thread'

如果删除了循环,tm()的返回值将作为单个参数传递给start_new_thread,这会导致发布原始错误。

线程

如其他答案中所述,您可能应该使用threading库而不是threadMore details about why are listed here.