Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running python script inside ipython

People also ask

How do I run a Python script in IPython?

To do this, first start the terminal program to get a command prompt. Then give the command ipython3 and press enter. Then you can write Python commands and execute them by pressing enter. Note that IPython supports tab completion.

How do I run a .py file in Jupyterlab?

Some simple options: Open a terminal in Jupyter, run your Python scripts in the terminal like you would in your local terminal. Make a notebook, and use %run <name of script.py> as an entry in a cell.

How do I import files into IPython?

A text file can be loaded in a notebook cell with the magic command %load . the content of filename.py will be loaded in the next cell. You can edit and execute it as usual. To save the cell content back into a file add the cell-magic %%writefile filename.py at the beginning of the cell and run it.


from within the directory of "my_script.py" you can simply do:

%run ./my_script.py

How to run a script in Ipython

import os
filepath='C:\\Users\\User\\FolderWithPythonScript' 
os.chdir(filepath)
%run pyFileInThatFilePath.py

That should do it


The %run magic has a parameter file_finder that it uses to get the full path to the file to execute (see here); as you note, it just looks in the current directory, appending ".py" if necessary.

There doesn't seem to be a way to specify which file finder to use from the %run magic, but there's nothing to stop you from defining your own magic command that calls into %run with an appropriate file finder.

As a very nasty hack, you could override the default file_finder with your own:

IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder

To be honest, at the rate the IPython API is changing that's as likely to continue to work as defining your own magic is.


In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.

Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts

There is also a builtin function execfile(filename) that will do what you want


Not exactly the answer to your question, but you can drop into ipython at the end of a script's execution by using the -i parameter to ipython:

ipython -i my_script.py

At the end of the script you're dropped into the ipython prompt with the script's variables available to you, just like python -i.