循环cod时获取输入

2024-04-27 02:45:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一个Twitter机器人,它在我的时间轴中从Twitter流推特。不管它做什么,我怎么能在接收tweet(循环代码)的同时发送tweet(获取键盘输入)。你知道吗

这不是一个关于twitterapi的问题,只是一个关于如何在循环代码时获取输入的一般性问题。你知道吗


Tags: 代码机器人twittertweet时间轴twitterapi键盘输入
3条回答

也许,你在找这样的东西

userInput = raw_input()

while(userInput != q):
    #do something
    userInput = raw_input()

我知道您不希望循环等待您在每次迭代中输入tweet,因此不能使用最常用的方法raw\u input。你知道吗

在这种情况下,它是特定于平台的。对于Unix系统,您应该使用select模块,而在Windows中,您应该使用msvcrt模块。你知道吗

使用select,我们的想法是在每次迭代中检查stdin,并在得到一个stdin时处理消息。你知道吗

比如:

import sys
import select

while True:
    message = select.select([sys.stdin], [], [], timeout=0.1)[0]
    if message:
        print(message)

我会为它创建一个特定的线程,当使用它时,我会调用你的twitterapi post函数。(但这取决于代码的结构)

import threading

t1 = threading.Thread(target=post_from_keyboard)
t1.start()
t1.join()   

# Loop exits when users writes quit. 
# Obviously it won't post any Tweets with the word "quit"    
def post_from_keyboard():
    while(True):   
        kb_tweet = input("Enter Tweet or write "quit" to exit")
        if kb_tweet != "quit"
            your_tweet_api_call( kb_tweet )
        else:
            break

相关问题 更多 >