Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is it possible to run a python script (not module) from inside ipython without indicating its path? I tried to set PYTHONPATH but it seems to work only for modules. I would like to execute

%run my_script.py

without being in the directory containing the file.

share|improve this question
import <module> is essentially the same as exec(<moduleSource>) in JavaScript or Perl. – Vortico Jul 31 '12 at 17:52
+1 for the syntax %run abc.py -- was trying to look for that – Sid Kshatriya May 3 at 9:40

2 Answers

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

share|improve this answer
That is also what I thought. However, in practice modules can be imported but scripts are not found by the interpreter unless started from the directory they belong to. – Tyler Durden Jul 31 '12 at 17:59
Read docs.python.org/tutorial/modules.html#the-module-search-path for more info. It details where it must be put for python to find the file, More specifically, many modules can double as scripts using the "if __name__ == '__main__':" line at the end – Snakes and Coffee Jul 31 '12 at 18:06

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.