Running python script inside ipython

前端 未结 5 853
无人及你
无人及你 2020-12-04 08:08

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

相关标签:
5条回答
  • 2020-12-04 08:29

    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

    0 讨论(0)
  • 2020-12-04 08:32

    for Python 3.6.5

    import os
    os.getcwd()
    runfile('testing.py')
    
    0 讨论(0)
  • 2020-12-04 08:38

    How to run a script in Ipython

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

    That should do it

    0 讨论(0)
  • 2020-12-04 08:49

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

    %run ./my_script.py
    
    0 讨论(0)
  • 2020-12-04 08:50

    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.

    0 讨论(0)
提交回复
热议问题