Skip to main content
 首页 » 编程设计

python之从 ipython 运行 python 程序

2024年10月24日8xing901022

我正在尝试从 ipython notebook 运行 python 程序。如果在命令下运行,它有效。

run twitterstream.py >> output.txt  

但是,如果使用 while 循环运行,会失败。不知道为什么会失败?

import time 
t_end = time.time() + 60 * 3 
while time.time() < t_end: 
    print ('entered') 
    run twitterstream.py >> output.txt  

语法错误:

File "<ipython-input-28-842e0185b3a8>", line 5 
    run twitterstream.py >> output.txt 
                    ^ 
SyntaxError: invalid syntax 

请您参考如下方法:

您的 while 语句结构正确。虽然它会尽可能多次打印“entered”直到 180 秒过去(这是很多次),并且它还会尝试以相同的方式调用您的脚本。每 1、5、10 秒或任何秒数只调用一次脚本可能会更好,因为没有必要经常调用它。

正如 Tadhg McDonald-Jensen 使用 %run 所指出的,您将能够调用您的脚本。此外,您必须考虑对 Twitter 的调用率有限制,请参阅 here .基本上每 15 分钟 15 次或每 15 分钟 180 次,但我不确定哪个适用于此。

假设最坏情况是每 15 分钟 15 次,您可以在三分钟的窗口内运行 15 次调用。所以你可以这样做:

from math import floor 
 
temp = floor(time.time()) 
    while time.time() < t_end: 
        if floor(time.time()) == temp + 12: 
            %run twitterstream.py >> output.txt 
        temp = floor(time.time()) 

这将每 12 秒调用一次您的脚本。