在ipython中运行python脚本

问题:在ipython中运行python脚本

是否可以从ipython内部运行python脚本(而不是模块)而不指示其路径?我尝试设置PYTHONPATH,但它似乎仅适用于模块。我想执行

%run my_script.py

而不在包含文件的目录中。

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.


回答 0

从“ my_script.py”目录中,您可以简单地执行以下操作:

%run ./my_script.py

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

%run ./my_script.py

回答 1

如何在Ipython中运行脚本

import os
filepath='C:\\Users\\User\\FolderWithPythonScript' 
os.chdir(filepath)
%run pyFileInThatFilePath.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


回答 2

%run魔术有一个参数file_finder,它使用来获取完整路径文件来执行(见这里); 如您所述,它只是在当前目录中查找,如有必要,附加“ .py”。

似乎没有要到指定的文件取景器使用方式,从%run魔术,但没有什么可以从定义自己的魔法命令阻止你在调用%run用适当的文件查找。

作为一个非常讨厌的黑客,您可以file_finder使用自己的默认设置覆盖默认设置:

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

坦白地说,按照IPython API的变化速度,它与定义您自己的魔术一样可能继续起作用。

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.


回答 3

在python中,模块和脚本之间没有区别;您可以同时执行脚本和模块。该文件必须位于pythonpath AFAIK上,因为python必须能够找到有问题的文件。如果从目录执行python,则该目录会自动添加到pythonpath中。

请参阅什么是从另一个Python脚本调用Python脚本的最佳方法?有关模块和脚本的更多信息

还有一个内置函数execfile(filename)将执行您想要的操作

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


回答 4

适用于Python 3.6.5

import os
os.getcwd()
runfile('testing.py')

for Python 3.6.5

import os
os.getcwd()
runfile('testing.py')