开发者

How can I get a file to autorun before I run any command in ipython?

开发者 https://www.devze.com 2023-02-28 09:46 出处:网络
I have a python file that holds a bunch of functions that I\'m continually modifying and then testing in ipython.My current workflo开发者_StackOverflow中文版w is to run \"%run myfile.py\" before each

I have a python file that holds a bunch of functions that I'm continually modifying and then testing in ipython. My current workflo开发者_StackOverflow中文版w is to run "%run myfile.py" before each command. However, ideally, I'd like that just to happen automatically. Is that possible?


If you really want to use rlwrap for this, write a filter! Just define an input_handler that adds %run myfile.py to the input, and an echo_handler to echo your original input so that you won't see this happening (man RlwrapFilter tells you all you ever wanted to know about filter writing, and then some).

But isn't it more elegant to solve this within ipython itself, using IPython.hooks.pre_runcode_hook?

import os
import IPython
ip = IPython.ipapi.get()

def runMyFile(self):
    ip.magic('%run myFile.py')
    raise IPython.ipapi.TryNext()

ip.set_hook('pre_runcode_hook', runMyFile)


I can't find any elegant way. This is the ugly way. Run:

rlwrap awk '{print "%run myfile.py"} {print} {fflush()}' |ipython

This reads from STDIN, but prints the command you wanted before each command. fflush is there to disable buffering and pass things to ipython immediately. rlwrap is there to keep the readline bindings; you can remove it if you don't have it, but this will be less convenient (no arrow keys, etc.).

Mind that you will have to type your commands before the ipython prompt appears. There might be other more annoying things which break, I haven't tested thoroughly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号