python如何在所有线程结束后执行最后操作,当主线程仍在python中运行时如何使用线程获取实时用户输入...

In the WHILE loop, I wanna run two function, one is base function, which will run everytime, the other is user_input function, when user input 'disarm', program can run user_input function.

This two function need in WHILE loop so can run all the time.

How could I do to write a function to accomplish this?

Because its realtime so I cant add time.sleep in threading.

Thanks.

import threading

class BackInput(threading.Thread):

def __init__(self):

super(BackInput, self).__init__()

def run(self):

self.input = raw_input()

while True:

threading1 = BackInput()

threading1.start()

threading1.join()

if threading1.input == 'disarm':

print 'Disarm'

break

print 'Arm'

In this code, the program should print Arm every second, when I typed disarm, it can print Disarm and break it.

解决方案

You really need to be more specific. Why do these need to be in threads? You should show us what you have tried, or describe in more detail what you are trying to accomplish.

In your current setup, you are putting the thread inside a loop, so it can't run independently of each user input.

edited: here is some cleaned up code as an example for you, based on your post edits and comments.

import threading

import time

import sys

def background():

while True:

time.sleep(3)

print 'disarm me by typing disarm'

def other_function():

print 'You disarmed me! Dying now.'

# now threading1 runs regardless of user input

threading1 = threading.Thread(target=background)

threading1.daemon = True

threading1.start()

while True:

if raw_input() == 'disarm':

other_function()

sys.exit()

else:

print 'not disarmed'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值