Running python script inside ipython

Is it possible to run a python script (not a module) from within ipython without specifying its path? I tried installing PYTHONPATH, but it seems to work only for modules. I would like to perform

%run my_script.py 

not being in the directory containing the file.

+104
python path ipython
Jul 31 '12 at 15:55
source share
5 answers

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

 %run ./my_script.py 
+89
Mar 12 '15 at 16:44
source share

How to run a script in ipython

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

It should do it

+21
Feb 11 '15 at 19:12
source share

In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be in 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 invoke a Python script from another Python script? for more information on modules and scripts

There is also a built-in function execfile (file name) that will do what you want

+16
Jul 31. 2018-12-12T00:
source share

The magic of %run has the file_finder parameter, which is used to get the full path to the executable file (see here ); as you noticed, it just looks in the current directory, adding ".py" if necessary.

There seems to be no way to indicate which file finder to use from the magic of %run , but you have nothing to stop you from defining your own magic command, which calls %run using the appropriate file search.

As a very nasty hack, you can override the standard file_finder with file_finder :

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

Honestly, with a change to the IPython API, which is likely to continue to work as a definition of your own magic.

+15
Jul 31 '12 at 18:13
source share

for Python 3.6.5 import os os.getcwd () runfile ('testing.py')

0
Apr 16 '19 at 16:10
source share



All Articles