如何在python解释器中执行文件?

问题:如何在python解释器中执行文件?

我正在尝试从解释器中使用python命令执行文件。

编辑:我正在尝试使用该文件中的变量和设置,而不是调用一个单独的进程。

I’m trying to execute a file with python commands from within the interpreter.

EDIT: I’m trying to use variables and settings from that file, not to invoke a separate process.


回答 0

几种方法。

从外壳

python someFile.py

从IDLE内部,按F5

如果您是交互式输入,请尝试以下操作:(仅适用于Python 2!)

>>> variables= {}
>>> execfile( "someFile.py", variables )
>>> print variables # globals from the someFile module

对于Python3,请使用:

>>> exec(open("filename.py").read())

Several ways.

From the shell

python someFile.py

From inside IDLE, hit F5.

If you’re typing interactively, try this: (Python 2 only!)

>>> variables= {}
>>> execfile( "someFile.py", variables )
>>> print variables # globals from the someFile module

For Python3, use:

>>> exec(open("filename.py").read())

回答 1

对于Python 2:

>>> execfile('filename.py')

对于Python 3:

>>> exec(open("filename.py").read())
# or
>>> from pathlib import Path
>>> exec(Path("filename.py").read_text())

请参阅文档。如果您使用的是Python 3.0,请参见此问题

有关执行后如何从filename.py访问全局变量的示例,请参见@ S.Lott的答案。

For Python 2:

>>> execfile('filename.py')

For Python 3:

>>> exec(open("filename.py").read())
# or
>>> from pathlib import Path
>>> exec(Path("filename.py").read_text())

See the documentation. If you are using Python 3.0, see this question.

See answer by @S.Lott for an example of how you access globals from filename.py after executing it.


回答 2

Python 2 + Python 3

exec(open("./path/to/script.py").read(), globals())

这将执行一个脚本并将其所有全局变量放入解释器的全局范围(在大多数脚本环境中是正常行为)。

Python 3 exec文档

Python 2 + Python 3

exec(open("./path/to/script.py").read(), globals())

This will execute a script and put all it’s global variables in the interpreter’s global scope (the normal behavior in most scripting environments).

Python 3 exec Documentation


回答 3

感到惊讶的是我还没有看到这个。您可以执行一个文件,然后在执行终止后使用以下-i选项使解释器保持打开状态:

| foo.py |
----------
testvar = 10

def bar(bing):
  return bing*3

--------



$ python -i foo.py
>>> testvar 
10
>>> bar(6)
18

Surprised I haven’t seen this yet. You can execute a file and then leave the interpreter open after execution terminates using the -i option:

| foo.py |
----------
testvar = 10

def bar(bing):
  return bing*3

--------



$ python -i foo.py
>>> testvar 
10
>>> bar(6)
18

回答 4

我正在尝试使用该文件中的变量和设置,而不是调用一个单独的进程。

好了,只需使用import filename(减.py,需要在同一目录中或上PYTHONPATH)导入文件即可运行该文件,使其变量,函数,类等在filename.variable命名空间中可用。

因此,如果您有cheddar.py垃圾邮件变量和函数鸡蛋,则可以使用导入它们import cheddar,通过来访问变量cheddar.spam并通过调用来运行函数cheddar.eggs()

如果您的代码位于cheddar.py函数之外,那么它将立即运行,但是构建在导入时运行内容的应用程序将使重用代码变得困难。如果可能的话,请将所有内容放入函数或类中。

I’m trying to use variables and settings from that file, not to invoke a separate process.

Well, simply importing the file with import filename (minus .py, needs to be in the same directory or on your PYTHONPATH) will run the file, making its variables, functions, classes, etc. available in the filename.variable namespace.

So if you have cheddar.py with the variable spam and the function eggs – you can import them with import cheddar, access the variable with cheddar.spam and run the function by calling cheddar.eggs()

If you have code in cheddar.py that is outside a function, it will be run immediately, but building applications that runs stuff on import is going to make it hard to reuse your code. If a all possible, put everything inside functions or classes.


回答 5

我认为最好的方法是:

import yourfile

并在修改yourfile.py之后

reload(yourfile)   

要么

import imp; 
imp.reload(yourfile) in python3

但这会使函数和类看起来像:yourfile.function1,yourfile.class1 …..

如果您不能接受,那么最终的解决方案是:

reload(yourfile)
from yourfile import *

From my view, the best way is:

import yourfile

and after modifying yourfile.py

reload(yourfile)   

or

import imp; 
imp.reload(yourfile) in python3

but this will make the function and classes looks like that: yourfile.function1, yourfile.class1…..

If you cannot accept those, the finally solution is:

reload(yourfile)
from yourfile import *

回答 6

我不是专家,但这是我注意到的:

例如,如果您的代码是mycode.py,而您只键入“ import mycode”,则Python将执行该代码,但不会使您的所有变量都可用于解释器。我发现如果要将所有变量提供给解释器,则应键入“ from mycode import *”。

I am not an expert but this is what I noticed:

if your code is mycode.py for instance, and you type just ‘import mycode’, Python will execute it but it will not make all your variables available to the interpreter. I found that you should type actually ‘from mycode import *’ if you want to make all variables available to the interpreter.


回答 7

做就是了,

from my_file import *

确保不添加.py扩展名。如果您使用子目录中的.py文件,

from my_dir.my_file import *

Just do,

from my_file import *

Make sure not to add .py extension. If your .py file in subdirectory use,

from my_dir.my_file import *

回答 8

对于python3使用或者与xxxx = nameyourfile

exec(open('./xxxx.py').read())

For python3 use either with xxxx = name of yourfile.

exec(open('./xxxx.py').read())

回答 9

对于Python 3:

>>> exec(open("helloworld.py").read())

运行命令之前,请确保您位于正确的目录中。

要从其他目录运行文件,可以使用以下命令:

with open ("C:\\Users\\UserName\\SomeFolder\\helloworld.py", "r") as file:
    exec(file.read())

For Python 3:

>>> exec(open("helloworld.py").read())

Make sure that you’re in the correct directory before running the command.

To run a file from a different directory, you can use the below command:

with open ("C:\\Users\\UserName\\SomeFolder\\helloworld.py", "r") as file:
    exec(file.read())

回答 10

假设您需要以下功能:

  1. 源文件在调试器中的行为正常(文件名显示在堆栈中,等等)
  2. __name__ == '__main__' 为True,因此脚本可以像脚本一样正常运行。

exec(open('foo.py').read())故障特征1的import foo策略失败,功能2

要获得两者,您需要这样做:

    source = open(filename).read()
    code = compile(source, filename, 'exec')
    exec(code)

Supposing you desire the following features:

  1. Source file behaves properly in your debugger (filename shows in stack, etc)
  2. __name__ == '__main__' is True so scripts behave properly as scripts.

The exec(open('foo.py').read()) fails feature 1 The import foo strategy fails feature 2

To get both, you need this:

    source = open(filename).read()
    code = compile(source, filename, 'exec')
    exec(code)