简体   繁体   English

从 ipython 运行 python 程序

[英]run python program from ipython

I'm trying to run python program from ipython notebook.我正在尝试从 ipython notebook 运行 python 程序。 If run below command it's works.如果在命令下运行,它就可以工作。

run twitterstream.py >> output.txt 

However if run with while loop it fails .但是,如果使用 while 循环运行它会失败 I don't know why it fails?不知道为什么会失败?

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

Syntax error:语法错误:

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

Your while statement is structured properly.您的 while 语句结构正确。 Although it will print "entered" as many times as possible until 180 seconds has elapsed (that's a lot of times), and it will also try to call your script in the same way.尽管它会尽可能多地打印“entered”,直到 180 秒过去(这是很多次),它也会尝试以相同的方式调用您的脚本。 You would likely be better served by only calling your script once every 1,5,10, or whatever number of seconds as it is unnecessary to call it constantly.每 1、5、10 或任何秒数只调用一次脚本可能会更好地为您服务,因为没有必要不断调用它。

As pointed out by Tadhg McDonald-Jensen using %run you will be able to call your script.正如 Tadhg McDonald-Jensen 所指出的,使用 %run 您将能够调用您的脚本。 Also there are limits to the rate of calls to twitter that you must consider see here .此外,您必须考虑对 twitter 的调用率有限制,请参阅此处 Basically 15 per 15 minutes or 180 per 15 minutes, though I'm not sure which applies here.基本上每 15 分钟 15 次或每 15 分钟 180 次,但我不确定哪个适用于此。

Assuming 15 per 15 minutes worst case scenario, you could run 15 calls in your three minute window.假设最坏的情况是每 15 分钟 15 次,您可以在三分钟的时间内运行 15 次调用。 So you could do something like:所以你可以这样做:

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())

This would call your script every 12 seconds.这将每 12 秒调用一次您的脚本。

the run "magic command" is not valid python code or syntax. run “魔术命令”不是有效的 Python 代码或语法。

If you want to use the magic commands from code you need to reference How to run an IPython magic from a script (or timing a Python script)如果您想使用代码中的魔法命令,您需要参考如何从脚本运行 IPython 魔法(或对 Python 脚本计时)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM