6

I'd like to be able to use %cd "default_dir" and %matplotlib whenever I call ipython from my terminal. I tried writing this in a .py file in .ipython/profile_default/startup/file.py but it results in the following error:

[TerminalIPythonApp] WARNING | Unknown error in handling startup files:
  File "/Users/<name>/Dropbox/.ipython/profile_default/startup/startup.py", line 18
    %cd "~/Dropbox/"
    ^
SyntaxError: invalid syntax
Luke Davis
  • 2,548
  • 2
  • 21
  • 43

2 Answers2

4

You just need to use the magic in your startup scripts:

get_ipython().magic('cd ~/Dropbox')
get_ipython().magic('matplotlib')

Put that in the contents of your startup script and it should do the magic you need ✨✨

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
  • Can you give a short explanation of why your answer works, or link me to any useful sources? Can't seem to find anything. – Luke Davis Jan 10 '17 at 21:01
  • I searched for something like "ipython pass variable to magic function", which turned up [this answer](http://stackoverflow.com/a/14409510/344286), which was exactly the result you wanted. – Wayne Werner Jan 10 '17 at 22:04
4

I just wanted to elaborate the Wayne's answer, but do not have enough reputation to do a comment. You can have the following in the start up script to run the required magic commands

from IPython.core import getipython

getipython.get_ipython().run_line_magic("reload_ext", "autoreload")
getipython.get_ipython().run_line_magic("autoreload", "2")

Module reference is here Ipython module

To run the above start up at terminal, do this

ipython -i startup.py
Mossab
  • 818
  • 8
  • 13
vkt
  • 439
  • 5
  • 6
  • Very helpful. For those searching, note that you can localize the startup script folder by typing `get_ipython().profile_dir.startup_dir` – Dr_Zaszuś Nov 25 '20 at 16:42