如何运行您的Python脚本

One of the most important skills you need to build as a Python developer is to be able to run Python scripts and code. This is going to be the only way for you to know if your code works as you planned. It’s even the only way of knowing if your code works at all!

作为Python开发人员,您需要构建的最重要的技能之一就是能够运行Python脚本和代码。 这将是您知道代码是否按计划工作的唯一方法。 它甚至是知道您的代码是否完全有效的唯一方法!

This step-by-step tutorial will guide you through a series of ways to run Python scripts, depending on your environment, platform, needs, and skills as a programmer.

本分步指南将根据您的环境,平台,需求和程序员的技能,指导您完成一系列运行Python脚本的方法。

You’ll have the opportunity to learn how to run Python scripts by using:

您将有机会使用以下方法来学习如何运行Python脚本:

  • The operating system command-line or terminal
  • The Python interactive mode
  • The IDE or text editor you like best
  • The file manager of your system, by double-clicking on the icon of your script
  • 操作系统命令行或终端
  • Python互动模式
  • 您最喜欢的IDE或文本编辑器
  • 双击脚本图标,即可创建系统文件管理器

This way, you’ll get the knowledge and skills you’ll need to make your development cycle more productive and flexible.

这样,您将获得使开发周期更加高效和灵活所需的知识和技能。

Free Bonus: Click here to get access to a chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

免费红利: 单击此处可访问Python技巧的一章:该书通过简单的示例向您展示了Python的最佳实践,您可以立即应用这些示例编写更精美的Pythonic代码。

脚本与模块 (Scripts vs Modules)

In computing, the word script is used to refer to a file containing a logical sequence of orders or a batch processing file. This is usually a simple program, stored in a plain text file.

在计算中,脚本脚本用于指代包含订单逻辑顺序的文件或批处理文件。 这通常是一个简单的程序,存储在纯文本文件中。

Scripts are always processed by some kind of interpreter, which is responsible for executing each command sequentially.

脚本始终由某种解释器处理,该解释器负责按顺序执行每个命令。

A plain text file containing Python code that is intended to be directly executed by the user is usually called script, which is an informal term that means top-level program file.

旨在由用户直接执行的包含Python代码的纯文本文件通常称为script ,这是一个非正式术语,表示顶级程序文件

On the other hand, a plain text file, which contains Python code that is designed to be imported and used from another Python file, is called module.

另一方面,包含设计用于从另一个Python文件导入和使用的Python代码的纯文本文件称为module

So, the main difference between a module and a script is that modules are meant to be imported, while scripts are made to be directly executed.

因此,模块和脚本之间的主要区别在于模块是要导入的 ,而脚本是直接执行的

In either case, the important thing is to know how to run the Python code you write into your modules and scripts.

无论哪种情况,重要的是要知道如何运行您写入模块和脚本中的Python代码。

什么是Python解释器? (What’s the Python Interpreter?)

Python is an excellent programming language that allows you to be productive in a wide variety of fields.

Python是一种出色的编程语言,可让您在各种领域中高效工作

Python is also a piece of software called an interpreter. The interpreter is the program you’ll need to run Python code and scripts. Technically, the interpreter is a layer of software that works between your program and your computer hardware to get your code running.

Python还是称为解释器的软件。 解释器是运行Python代码和脚本所需的程序。 从技术上讲,解释器是一层软件,可以在您的程序和计算机硬件之间运行,以使代码运行。

Depending on the Python implementation you use, the interpreter can be:

根据您使用的Python实现,解释器可以是:

  • A program written in C, like CPython, which is the core implementation of the language
  • A program written in Java, like Jython
  • A program written in Python itself, like PyPy
  • A program implemented in .NET, like IronPython
  • 用C编写的程序,例如CPython ,是该语言的核心实现
  • 用Java编写的程序,例如Jython
  • 用Python本身编写的程序,例如PyPy
  • 在.NET中实现的程序,例如IronPython

Whatever form the interpreter takes, the code you write will always be run by this program. Therefore, the first condition to be able to run Python scripts is to have the interpreter correctly installed on your system.

无论解释器采用哪种形式,您编写的代码将始终由该程序运行。 因此,能够运行Python脚本的首要条件是在系统上正确安装解释器

The interpreter is able to run Python code in two different ways:

解释器能够以两种不同的方式运行Python代码:

  • As a script or module
  • As a piece of code typed into an interactive session
  • 作为脚本或模块
  • 作为一段代码输入到交互式会话中

如何以交互方式运行Python代码 (How to Run Python Code Interactively)

A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python, or python3 depending on your Python installation, and then hit Enter.

运行Python代码的一种广泛使用的方式是通过交互式会话。 要启动Python交互式会话,只需打开命令行或终端,然后根据您的Python安装键入pythonpython3 ,然后按Enter即可

Here’s an example of how to do this on Linux:

这是如何在Linux上执行此操作的示例:

 $ python3
$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
Type "help", "copyright", "credits" or "license" for more information.
>>>
> >>

The standard prompt for the interactive mode is >>>, so as soon as you see these characters, you’ll know you are in.

交互式模式的标准提示是>>> ,因此一旦您看到这些字符,便会知道自己在其中。

Now, you can write and run Python code as you wish, with the only drawback being that when you close the session, your code will be gone.

现在,您可以根据需要编写和运行Python代码,唯一的缺点是,当关闭会话时,您的代码将消失。

When you work interactively, every expression and statement you type in is evaluated and executed immediately:

当您进行交互工作时,您输入的每个表达式和语句都将立即求值并执行:

>>>
>>>
 >>>  print ( 'Hello World!' )
Hello World!
>>>  2 + 5
7
>>>  print ( 'Welcome to Real Python!' )
Welcome to Real Python!

An interactive session will allow you to test every piece of code you write, which makes it an awesome development tool and an excellent place to experiment with the language and test Python code on the fly.

交互式会话将使您能够测试您编写的每段代码,这使其成为一个了不起的开发工具,并且是尝试使用该语言并即时测试Python代码的绝佳场所。

To exit interactive mode, you can use one of the following options:

要退出交互模式,可以使用以下选项之一:

  • quit() or exit(), which are built-in functions
  • The Ctrl+Z and Enter key combination on Windows, or just Ctrl+D on Unix-like systems
  • quit()exit() ,它们是内置函数
  • 在Windows上按Ctrl + ZEnter键组合,或者在类似Unix的系统上仅按Ctrl + D

Note: The first rule of thumb to remember when using Python is that if you’re in doubt about what a piece of Python code does, then launch an interactive session and try it out to see what happens.

注意:使用Python时要记住的第一条经验法则是,如果您不确定一段Python代码的功能,请启动一个交互式会话并尝试一下以查看会发生什么。

If you’ve never worked with the command-line or terminal, then you can try this:

如果您从未使用过命令行或终端,则可以尝试以下操作:

  • On Windows, the command-line is usually known as command prompt or MS-DOS console, and it is a program called cmd.exe. The path to this program can vary significantly from one system version to another.

    A quick way to get access to it is by pressing the Win+R key combination, which will take you to the Run dialog. Once you’re there, type in cmd and press Enter.

  • On GNU/Linux (and other Unixes), there are several applications that give you access to the system command-line. Some of the most popular are xterm, Gnome Terminal, and Konsole. These are tools that run a shell or terminal like Bash, ksh, csh, and so on.

    In this case, the path to these applications is much more varied and depends on the distribution and even on the desktop environment you use. So, you’ll need to read your system documentation.

  • On Mac OS X, you can access the system terminal from Applications → Utilities → Terminal.

  • 在Windows上,命令行通常称为命令提示符或MS-DOS控制台,它是一个名为cmd.exe的程序。 从一个系统版本到另一个系统版本,此程序的路径可能会有很大不同。

    快速访问它的方法是按Win + R组合键,这将带您进入“运行”对话框。 cmd输入 cmd并按Enter

  • 在GNU / Linux(和其他Unix)上,有几个应用程序可让您访问系统命令行。 最受欢迎的是xterm,Gnome Terminal和Konsole。 这些是运行Shell或终端程序(如Bash,ksh,csh等)的工具。

    在这种情况下,通向这些应用程序的路径会更加多种多样,并取决于分布甚至您使用的桌面环境。 因此,您需要阅读系统文档。

  • 在Mac OS X上,您可以从应用程序→实用程序→终端访问系统终端。

口译员如何运行Python脚本? (How Does the Interpreter Run Python Scripts?)

When you try to run Python scripts, a multi-step process begins. In this process the interpreter will:

当您尝试运行Python脚本时,将开始一个多步骤过程。 在此过程中,口译员将:

  1. Process the statements of your script in a sequential fashion

  2. Compile the source code to an intermediate format known as bytecode

    This bytecode is a translation of the code into a lower-level language that’s platform-independent. Its purpose is to optimize code execution. So, the next time the interpreter runs your code, it’ll bypass this compilation step.

    Strictly speaking, this code optimization is only for modules (imported files), not for executable scripts.

  3. Ship off the code for execution

    At this point, something known as a Python Virtual Machine (PVM) comes into action. The PVM is the runtime engine of Python. It is a cycle that iterates over the instructions of your bytecode to run them one by one.

    The PVM is not an isolated component of Python. It’s just part of the Python system you’ve installed on your machine. Technically, the PVM is the last step of what is called the Python interpreter.

  1. 以顺序方式处理脚本的语句

  2. 将源代码编译为称为字节码的中间格式

    该字节码是将代码翻译成与平台无关的较低级语言的方法。 其目的是优化代码执行。 因此,下次解释器运行您的代码时,它将绕过此编译步骤。

    严格来说,此代码优化仅适用于模块(导入的文件),而不适用于可执行脚本。

  3. 交付代码以执行

    此时,称为Python虚拟机(PVM)的东西开始起作用。 PVM是Python的运行时引擎。 这是一个循环,遍历字节码的指令以逐一运行它们。

    PVM不是Python的独立组件。 它只是您安装在计算机上的Python系统的一部分。 从技术上讲,PVM是所谓的Python解释器的最后一步。

The whole process to run Python scripts is known as the Python Execution Model.

运行Python脚本的整个过程称为Python执行模型

Note: This description of the Python Execution Model corresponds to the core implementation of the language, that is, CPython. As this is not a language requirement, it may be subject to future changes.

注意: Python执行模型的此描述对应于该语言的核心实现,即CPython。 由于这不是语言要求,因此可能会随时更改。

如何使用命令行运行Python脚本 (How to Run Python Scripts Using the Command-Line)

A Python interactive session will allow you to write a lot of lines of code, but once you close the session, you lose everything you’ve written. That’s why the usual way of writing Python programs is by using plain text files. By convention, those files will use the .py extension. (On Windows systems the extension can also be .pyw.)

Python交互式会话将允许您编写许多代码行,但是一旦关闭会话,您将丢失编写的所有内容。 这就是为什么编写Python程序的通常方法是使用纯文本文件。 按照约定,这些文件将使用.py扩展名。 (在Windows系统上,扩展名也可以是.pyw 。)

Python code files can be created with any plain text editor. If you are new to Python programming, you can try Sublime Text, which is a powerful and easy-to-use editor, but you can use any editor you like.

可以使用任何纯文本编辑器创建Python代码文件。 如果您不熟悉 Python编程,可以尝试Sublime Text ,它是一个功能强大且易于使用的编辑器,但是您可以使用任何喜欢的编辑器。

To keep moving forward in this tutorial, you’ll need to create a test script. Open your favorite text editor and write the following code:

为了继续前进,您需要创建一个测试脚本。 打开您喜欢的文本编辑器并编写以下代码:

Save the file in your working directory with the name hello.py. With the test script ready, you can continue reading.

将文件保存在您的工作目录中,名称为hello.py 。 准备好测试脚本后,您可以继续阅读。

使用python命令 (Using the python Command)

To run Python scripts with the python command, you need to open a command-line and type in the word python, or python3 if you have both versions, followed by the path to your script, just like this:

要使用python命令运行Python脚本,您需要打开命令行并输入pythonpython3如果您同时拥有这两个版本),然后输入脚本路径,如下所示:

 $ python3 hello.py
$ python3 hello.py
Hello World!
Hello World!

If everything works okay, after you press Enter, you’ll see the phrase Hello World! on your screen. That’s it! You’ve just run your first Python script!

如果一切正常,请按Enter键 ,您将看到短语Hello World! 在屏幕上。 而已! 您刚刚运行了第一个Python脚本!

If this doesn’t work right, maybe you’ll need to check your system PATH, your Python installation, the way you created the hello.py script, the place where you saved it, and so on.

如果此方法无法正常工作,则可能需要检查系统PATH ,Python安装, hello.py脚本的创建方式,保存位置等。

This is the most basic and practical way to run Python scripts.

这是运行Python脚本的最基本,最实用的方法。

重定向输出 (Redirecting the Output)

Sometimes it’s useful to save the output of a script for later analysis. Here’s how you can do that:

有时保存脚本的输出以供以后分析很有用。 这是您可以执行的操作:

This operation redirects the output of your script to output.txt, rather than to the standard system output (stdout). The process is commonly known as stream redirection and is available on both Windows and Unix-like systems.

此操作将脚本的输出重定向到output.txt ,而不是标准系统输出( stdout )。 该过程通常称为流重定向,并且在Windows和类似Unix的系统上都可用。

If output.txt doesn’t exist, then it’s automatically created. On the other hand, if the file already exists, then its contents will be replaced with the new output.

如果output.txt不存在,则会自动创建。 另一方面,如果文件已经存在,则其内容将被新的输出替换。

Finally, if you want to add the output of consecutive executions to the end of output.txt, then you must use two angle brackets (>>) instead of one, just like this:

最后,如果要将连续执行的输出添加到output.txt的末尾,则必须使用两个尖括号( >> )而不是一个尖括号,如下所示:

 $ python3 hello.py >> output.txt
$ python3 hello.py >> output.txt

Now, the output will be appended to the end of output.txt.

现在,输出将追加到output.txt的末尾。

使用-m选项运行模块 (Running Modules With the -m Option)

Python offers a series of command-line options that you can use according to your needs. For example, if you want to run a Python module, you can use the command python -m <module-name>.

Python提供了一系列命令行选项,您可以根据需要使用它们。 例如,如果要运行Python模块,则可以使用命令python -m <module-name>

The -m option searches sys.path for the module name and runs its content as __main__:

-m选项在sys.path中搜索模块名称,并将其内容作为__main__运行:

Note: module-name needs to be the name of a module object, not a string.

注意: module-name必须是模块对象的名称,而不是字符串。

使用脚本文件名 (Using the Script Filename)

On recent versions of Windows, it is possible to run Python scripts by simply entering the name of the file containing the code at the command prompt:

在最新版本的Windows上,只需在命令提示符下输入包含代码的文件名即可运行Python脚本:

 C:devspace> hello.py
C:devspace> hello.py
Hello World!
Hello World!

This is possible because Windows uses the system registry and the file association to determine which program to use for running a particular file.

这是可能的,因为Windows使用系统注册表和文件关联来确定使用哪个程序来运行特定文件。

On Unix-like systems, such as GNU/Linux, you can achieve something similar. You’ll only have to add a first line with the text #!/usr/bin/env python, just as you did with hello.py.

在类似Unix的系统(例如GNU / Linux)上,您可以实现类似的功能。 您只需添加#!/usr/bin/env python文本作为第一行,就像使用hello.py

For Python, this is a simple comment, but for the operating system, this line indicates what program must be used to run the file.

对于Python,这是一个简单的注释,但是对于操作系统,此行指示必须使用什么程序来运行该文件。

This line begins with the #! character combination, which is commonly called hash bang or shebang, and continues with the path to the interpreter.

该行以#!开头#! 字符组合,通常称为hash bangshebang ,并一直延续到解释器的路径。

There are two ways to specify the path to the interpreter:

有两种方法可以指定解释器的路径:

  • #!/usr/bin/python: writing the absolute path
  • #!/usr/bin/env python: using the operating system env command, which locates and executes Python by searching the PATH environment variable
  • #!/usr/bin/python编写绝对路径
  • #!/usr/bin/env python使用操作系统env命令,该命令通过搜索PATH环境变量来定位并执行Python

This last option is useful if you bear in mind that not all Unix-like systems locate the interpreter in the same place.

如果您要记住并非所有类Unix系统都将解释器放在同一位置,则最后一个选项很有用。

Finally, to execute a script like this one, you need to assign execution permissions to it and then type in the filename at the command-line.

最后,要执行这样的脚本,您需要为其分配执行权限,然后在命令行中输入文件名。

Here’s an example of how to do this:

这是有关如何执行此操作的示例:

With execution permissions and the shebang line properly configured, you can run the script by simply typing its filename at the command-line.

有了执行权限并正确配置了shebang行,您只需在命令行输入文件名即可运行脚本。

Finally, you need to note that if your script isn’t located at your current working directory, you’ll have to use the file path for this method to work correctly.

最后,您需要注意的是,如果脚本不在当前工作目录中,则必须使用文件路径使此方法正常工作。

如何交互运行Python脚本 (How to Run Python Scripts Interactively)

It is also possible to run Python scripts and modules from an interactive session. This option offers you a variety of possibilities.

也可以从交互式会话中运行Python脚本和模块。 此选项为您提供多种可能性。

利用import优势 (Taking Advantage of import)

When you import a module, what really happens is that you load its contents for later access and use. The interesting thing about this process is that import runs the code as its final step.

导入模块时 ,真正发生的事情是加载其内容以供以后访问和使用。 关于此过程的有趣之处在于, import将代码作为最后一步来运行。

When the module contains only classes, functions, variables, and constants definitions, you probably won’t be aware that the code was actually run, but when the module includes calls to functions, methods, or other statements that generate visible results, then you’ll witness its execution.

当模块仅包含类,函数,变量和常量定义时,您可能不会意识到代码实际上已在运行,但是当模块包含对产生可见结果的函数,方法或其他语句的调用时,您可以将见证其执行。

This provides you with another option to run Python scripts:

这为您提供了另一个运行Python脚本的选项:

>>>
>>> import hello
Hello World!

>>>

You’ll have to note that this option works only once per session. After the first import, successive import executions do nothing, even if you modify the content of the module. This is because import operations are expensive and therefore run only once. Here’s an example:

您必须注意,此选项每个会话仅工作一次。 第一次import后,即使您修改了模块的内容,后续的import执行也无济于事。 这是因为import操作很昂贵,因此只能运行一次。 这是一个例子:

>>>
>>> import hello  # Do nothing
>>> import hello  # Do nothing again

>>>

These two import operations do nothing, because Python knows that hello has already been imported.

这两个import操作无济于事,因为Python知道hello已经被导入。

There are some requirements for this method to work:

使用此方法有一些要求:

  • The file with the Python code must be located in your current working directory.
  • The file must be in the Python Module Search Path (PMSP), where Python looks for the modules and packages you import.

To know what’s in your current PMSP, you can run the following code:

要了解当前的PMSP中的内容,可以运行以下代码:

>>>
>>> import sys
>>> for path in sys.path:
...     print(path)
...
/usr/lib/python36.zip
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages

>>>

Running this code, you’ll get the list of directories and .zip files where Python searches the modules you import.

运行此代码,您将获得目录和.zip文件的列表,Python在其中搜索您导入的模块。

使用importlibimp (Using importlib and imp)

In the Python Standard Library, you can find importlib, which is a module that provides import_module().

Python标准库中 ,您可以找到importlib ,这是一个提供import_module()的模块。

With import_module(), you can emulate an import operation and, therefore, execute any module or script. Take a look at this example:

使用import_module() ,您可以模拟import操作,因此可以执行任何模块或脚本。 看一下这个例子:

>>>
>>> import importlib
>>> importlib.import_module('hello')
Hello World!
<module 'hello' from '/home/username/hello.py'>

>>>

Once you’ve imported a module for the first time, you won’t be able to continue using import to run it. In this case, you can use importlib.reload(), which will force the interpreter to re-import the module again, just like in the following code:

首次导入模块后,将无法继续使用import来运行它。 在这种情况下,可以使用importlib.reload() ,这将强制解释器再次重新导入模块,如以下代码所示:

>>>
>>> import hello  # First import
Hello World!
>>> import hello  # Second import, which does nothing
>>> import importlib
>>> importlib.reload(hello)
Hello World!
<module 'hello' from '/home/username/hello.py'>

>>>

An important point to note here is that the argument of reload() has to be the name of a module object, not a string:

这里要注意的重要一点是, reload()的参数必须是模块对象的名称,而不是字符串:

>>>
>>> importlib.reload('hello')
Traceback (most recent call last):
    ...
TypeError: reload() argument must be a module

>>>

If you use a string as an argument, then reload() will raise a TypeError exception.

如果使用字符串作为参数,则reload()将引发TypeError异常。

Note: The output of the previous code has been abbreviated (...) in order to save space.

注意:前面的代码的输出已缩写( ... ),以节省空间。

importlib.reload() comes in handy when you are modifying a module and want to test if your changes work, without leaving the current interactive session.

importlib.reload()在您修改模块并想要测试您的更改是否有效而无需离开当前交互式会话时会派上用场。

Finally, if you are using Python 2.x, then you’ll have imp, which is a module that provides a function called reload(). imp.reload() works similarly to importlib.reload(). Here’s an example:

最后,如果您使用的是Python 2.x,那么您将拥有imp ,这是一个提供名为reload()的功能的模块。 imp.reload()importlib.reload()类似。 这是一个例子:

>>>
>>> import hello  # First import
Hello World!
>>> import hello  # Second import, which does nothing
>>> import imp
>>> imp.reload(hello)
Hello World!
<module 'hello' from '/home/username/hello.py'>

>>>

In Python 2.x, reload() is a built-in function. In versions 2.6 and 2.7, it is also included in imp, to aid the transition to 3.x.

在Python 2.x中, reload()是一个内置函数。 在2.6和2.7版本中,它还包含在imp ,以帮助过渡到3.x。

Note: imp has been deprecated since version 3.4 of the language. The imp package is pending deprecation in favor of importlib.

注意:从该语言的3.4版开始,不推荐使用impimp包正在待弃用,以支持importlib

使用runpy.run_module()runpy.run_path() (Using runpy.run_module() and runpy.run_path())

The Standard Library includes a module called runpy. In this module, you can find run_module(), which is a function that allows you to run modules without importing them first. This function returns the globals dictionary of the executed module.

标准库包含一个名为runpy的模块。 在此模块中,您可以找到run_module() ,该函数使您无需先导入即可运行模块。 此函数返回已执行模块的globals字典。

Here’s an example of how you can use it:

这是一个如何使用它的示例:

>>>
>>> runpy.run_module(mod_name='hello')
Hello World!
{'__name__': 'hello',
    ...
'_': None}}

>>>

The module is located using a standard import mechanism and then executed on a fresh module namespace.

使用标准import机制定位模块,然后在新的模块名称空间上执行。

The first argument of run_module() must be a string with the absolute name of the module (without the .py extension).

run_module()的第一个参数必须是带有模块绝对名称的字符串(不带.py扩展名)。

On the other hand, runpy also provides run_path(), which will allow you to run a module by providing its location in the filesystem:

另一方面, runpy还提供了run_path() ,它允许您通过提供模块在文件系统中的位置来运行模块:

>>>
>>> import runpy
>>> runpy.run_path(file_path='hello.py')
Hello World!
{'__name__': '<run_path>',
    ...
'_': None}}

>>>

Like run_module(), run_path() returns the globals dictionary of the executed module.

run_module()run_path()返回已执行模块的globals字典。

The file_path parameter must be a string and can refer to the following:

file_path参数必须是字符串,并且可以引用以下内容:

  • The location of a Python source file
  • The location of a compiled bytecode file
  • The value of a valid entry in the sys.path, containing a __main__ module (__main__.py file)
  • Python源文件的位置
  • 编译后的字节码文件的位置
  • sys.path有效条目的值,其中包含__main__模块( __main__.py文件)

黑客exec() (Hacking exec())

So far, you’ve seen the most commonly used ways to run Python scripts. In this section, you’ll see how to do that by using exec(), which is a built-in function that supports the dynamic execution of Python code.

到目前为止,您已经了解了运行Python脚本的最常用方法。 在本节中,您将看到如何使用exec()做到这一点,这是一个内置函数,支持动态执行Python代码。

exec() provides an alternative way for running your scripts:

exec()提供了一种运行脚本的替代方法:

>>>
>>> exec(open('hello.py').read())
'Hello World!'

>>>

This statement opens hello.py, reads its content, and sends it to exec(), which finally runs the code.

该语句打开hello.py ,读取其内容,并将其发送到exec() ,该代码最终运行代码。

The above example is a little bit out there. It’s just a “hack” that shows you how versatile and flexible Python can be.

上面的示例在那里。 这只是一个“ hack”,向您展示Python的通用性和灵活性。

使用execfile() (仅适用于Python 2.x) (Using execfile() (Python 2.x Only))

If you prefer to use Python 2.x, you can use a built-in function called execfile(), which is able to run Python scripts.

如果您更喜欢使用Python 2.x,则可以使用一个名为execfile()的内置函数,该函数能够运行Python脚本。

The first argument of execfile() has to be a string containing the path to the file you want to run. Here’s an example:

execfile()的第一个参数必须是一个字符串,其中包含要运行的文件的路径。 这是一个例子:

>>>
>>> execfile('hello.py')
Hello World!

>>>

Here, hello.py is parsed and evaluated as a sequence of Python statements.

在这里, hello.py被解析并评估为一系列Python语句。

如何从IDE或文本编辑器运行Python脚本 (How to Run Python Scripts From an IDE or a Text Editor)

When developing larger and more complex applications, it is recommended that you use an integrated development environment (IDE) or an advanced text editor.

在开发更大,更复杂的应用程序时,建议您使用集成开发环境(IDE)或高级文本编辑器

Most of these programs offer the possibility of running your scripts from inside the environment itself. It is common for them to include a Run or Build command, which is usually available from the tool bar or from the main menu.

这些程序中的大多数都提供了从环境本身内部运行脚本的可能性。 通常,他们会包含一个“运行”或“构建”命令,通常可从工具栏或主菜单中获得该命令。

Python’s standard distribution includes IDLE as the default IDE, and you can use it to write, debug, modify, and run your modules and scripts.

Python的标准发行版包括IDLE作为默认IDE,您可以使用它编写,调试,修改和运行模块和脚本。

Other IDEs such as Eclipse-PyDev, PyCharm, Eric, and NetBeans also allow you to run Python scripts from inside the environment.

其他IDE(例如Eclipse-PyDev,PyCharm,Eri​​c和NetBeans)还允许您从环境内部运行Python脚本。

Advanced text editors like Sublime Text and Visual Studio Code also allow you to run your scripts.

诸如Sublime TextVisual Studio Code之类的高级文本编辑器还允许您运行脚本。

To grasp the details of how to run Python scripts from your preferred IDE or editor, you can take a look at its documentation.

要了解如何从首选的IDE或编辑器中运行Python脚本的详细信息,可以查看其文档。

如何从文件管理器运行Python脚本 (How to Run Python Scripts From a File Manager)

Running a script by double-clicking on its icon in a file manager is another possible way to run your Python scripts. This option may not be widely used in the development stage, but it may be used when you release your code for production.

通过在文件管理器中双击其图标来运行脚本是另一种运行Python脚本的方法。 此选项在开发阶段可能未得到广泛使用,但是当您发布生产代码时可能会使用该选项。

In order to be able to run your scripts with a double-click, you must satisfy some conditions that will depend on your operating system.

为了能够双击运行脚本,您必须满足某些条件,具体取决于您的操作系统。

Windows, for example, associates the extensions .py and .pyw with the programs python.exe and pythonw.exe respectively. This allows you to run your scripts by double-clicking on them.

例如,Windows将扩展名.py.pyw与程序python.exepythonw.exe 。 这使您可以通过双击运行脚本。

When you have a script with a command-line interface, it is likely that you only see the flash of a black window on your screen. To avoid this annoying situation, you can add a statement like input('Press Enter to Continue...') at the end of the script. This way, the program will stop until you press Enter.

当您具有带有命令行界面的脚本时,很可能您只能在屏幕上看到黑色窗口的闪烁。 为了避免这种烦人的情况,您可以在脚本末尾添加诸如input('Press Enter to Continue...')类的语句。 这样,程序将停止,直到您按Enter为止。

This trick has its drawbacks, though. For example, if your script has any error, the execution will be aborted before reaching the input() statement, and you still won’t be able to see the result.

但是,此技巧有其缺点。 例如,如果您的脚本有任何错误,执行将在到达input()语句之前被中止,您仍然看不到结果。

On Unix-like systems, you’ll probably be able to run your scripts by double-clicking on them in your file manager. To achieve this, your script must have execution permissions, and you’ll need to use the shebang trick you’ve already seen. Likewise, you may not see any results on screen when it comes to command-line interface scripts.

在类似Unix的系统上,您可以通过在文件管理器中双击脚本来运行它们。 为此,您的脚本必须具有执行权限,并且需要使用已经看到的shebang技巧。 同样,涉及命令行界面脚本时,屏幕上可能看不到任何结果。

Because the execution of scripts through double-click has several limitations and depends on many factors (such as the operating system, the file manager, execution permissions, file associations), it is recommended that you see it as a viable option for scripts already debugged and ready to go into production.

由于通过双击执行脚本有一些局限性,并且取决于许多因素(例如操作系统,文件管理器,执行权限,文件关联),因此建议您将其视为已调试脚本的可行选项。并准备投产。

结论 (Conclusion)

With the reading of this tutorial, you have acquired the knowledge and skills you need to be able to run Python scripts and code in several ways and in a variety of situations and development environments.

通过阅读本教程,您已经掌握了以多种方式以及在各种情况和开发环境下运行Python脚本和代码所需的知识和技能。

You are now able to run Python scripts from:

现在,您可以从以下位置运行Python脚本:

  • The operating system command-line or terminal
  • The Python interactive mode
  • The IDE or text editor you like best
  • The file manager of your system, by double-clicking on the icon of your script
  • 操作系统命令行或终端
  • Python互动模式
  • 您最喜欢的IDE或文本编辑器
  • 双击脚本图标,即可创建系统文件管理器

These skills will make your development process much faster, as well as more productive and flexible.

这些技能将使您的开发过程更快,更高效,更灵活。

翻译自: https://www.pybloggers.com/2019/02/how-to-run-your-python-scripts/

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值