prompt-toolkit / ptpython

A better Python REPL
BSD 3-Clause "New" or "Revised" License
5.18k stars 277 forks source link

Executing lines post-initialization of ipython shell #79

Open junkmechanic opened 8 years ago

junkmechanic commented 8 years ago

Hi Jonathan, Thanks for your efforts in building ptpython. Here is a patch to include a step during the ipython shell start up.

diff --git a/ptpython/ipython.py b/ptpython/ipython.py
index e338eda..77552b7 100644
--- a/ptpython/ipython.py
+++ b/ptpython/ipython.py
@@ -239,6 +239,25 @@ def initialize_extensions(shell, extensions):
                 shell.showtraceback()

+def execute_post_init_lines(shell, exec_lines):
+    """
+    Partial copy of 'InteractiveShellApp._run_exec_lines' from IPython.
+    """
+    try:
+        iter(exec_lines)
+    except TypeError:
+        pass  # no lines to execute
+    else:
+        for line in exec_lines:
+            try:
+                shell.run_cell(line, store_history=False)
+            except:
+                ipy_utils.warn.warn(
+                    "Error in executing line in user namespace: %s" % line +
+                    "\nCheck your config files in %s" % ipy_utils.path.get_ipython_dir())
+                shell.showtraceback()
+
+
 def embed(**kwargs):
     """
     Copied from `IPython/terminal/embed.py`, but using our `InteractiveShellEmbed` instead.
@@ -252,4 +271,5 @@ def embed(**kwargs):
         kwargs['config'] = config
     shell = InteractiveShellEmbed.instance(**kwargs)
     initialize_extensions(shell, config['InteractiveShellApp']['extensions'])
+    execute_post_init_lines(shell, config['InteractiveShellApp']['exec_lines'])
     shell(header=header, stack_depth=2, compile_flags=compile_flags)

I believe you might have foreseen this during the conception. I didnt want to send a pull request because this is not the best solution. A better solution would be to implement the entire logic in init_code from shellapp.py . Nevertheless, if instead of including this in your next commit, you want me to submit a pull request, I dont mind doing that.

-Ankur

jonathanslenders commented 8 years ago

Hi @junkmechanic,

Thanks a lot for this! I'm not entirely sure whether the use of cell.run_cell, like in the original IPython code, is the best solution, but I'll have another look somewhere by the end of this week or next week. (Currently very busy and abroad...)

Cheers, Jonathan

actionless commented 2 years ago

have you got back home already? :3