Search code examples
editoripythonenthought

Setting the working directory of IPython Shell to that of the python file being executed in Canopy


I am new to IPython and I am using the Canopy distribution. The default value of the shell's working directory is /home/username. This is a bit painful, when I work on files which need other files present in the corresponding folder that I am working in.

So, I always manually change it to folder in which the file (which I am trying to execute) is present.

I found this relevant question, but my question is slightly different. Also, I couldn't understand the answer provided there really well.

Is there a shorter way of setting up the working directory of the IPython shell to that of the file on which I am working? Like a command?

Thanks for your help


Solution

  • This is a feature that is on our list of features, but quite low on priority. Canopy provides a right click context menu option to switch to the currently active editor's directory (see this).

    Also, as a temporary work-around, you could use the following macro to get your job done.

    # -*- coding: utf-8 -*-
    
    def run():
        code_task = get_active_task()
    
        from os.path import dirname
    
        def change_directory():
            code_editor = code_task.active_editor
            if not code_editor:
                return
            python_pane = code_task.python_pane
            active_dir = dirname(code_editor.obj.path)
            python_pane.execute_command(u'cd %s\n' % active_dir)
    
        code_task.on_trait_change(change_directory, 'active_editor') 
    

    Note: You'll have to run this macro, each time you have closed and reopened the editor window.

    See 1 and 2 for instructions on how to create a macro and for more information about macros in Canopy.