# FAQ：在 Windows 使用 Python

目錄

- FAQ：在 Windows 使用 Python

  - 在 Windows 作業系統裡我想執行 Python 程式，要怎麼做？

  - How do I make Python scripts executable?

  - Why does Python sometimes take so long to start?

  - How do I make an executable from a Python script?

  - Is a `*.pyd` file the same as a DLL?

  - How can I embed Python into a Windows application?

  - How do I keep editors from inserting tabs into my Python source?

  - How do I check for a keypress without blocking?

## 在 Windows 作業系統裡我想執行 Python 程式，要怎麼做？

這個問題的答案可能有點複雜。如果你經常使用「命令提示字元」執行程式，那這對你來說不會是什麼難事。如果不然，那就需要更仔細的說明了。

除非你在使用某种集成开发环境，否则你将会在被称为“DOS 窗口”或“命令提示符窗口”的地方 输入 Windows 命令。 通常你可以在搜索栏搜索 `cmd` 来创建这种窗口。 你应该能够识别你何时打开了这样的窗口，因为你将看到一个 Windows“命令提示符”，通常看起来是这样：

    C:\>

The letter may be different, and there might be other things after it, so you might just as easily see something like:

    D:\YourName\Projects\Python>

depending on how your computer has been set up and what else you have recently done with it. Once you have started such a window, you are well on the way to running Python programs.

You need to realize that your Python scripts have to be processed by another program called the Python interpreter. The interpreter reads your script, compiles it into bytecodes, and then executes the bytecodes to run your program. So, how do you arrange for the interpreter to handle your Python?

首先，确保命令窗口能够将“py”识别为指令来开启解释器。 如果你打开过一个命令窗口， 尝试输入命令 `py` 然后按回车：

    C:\Users\YourName> py

You should then see something like:

    Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>>

You have started the interpreter in "interactive mode". That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait. This is one of Python's strongest features. Check it by entering a few expressions of your choice and seeing the results:

    >>> print("Hello")
    Hello
    >>> "Hello" * 3
    'HelloHelloHello'

许多人把交互模式当作方便和高度可编程的计算器。 想结束交互式Python会话时，调用 `exit()` 函数，或者按住 `Ctrl` 键时输入 `Z` ，之后按 `Enter` 键返回Windows命令提示符。

你可能发现在开始菜单有这样一个条目 开始 ‣ 所有程序 ‣ Python 3.x ‣ Python (命令行)， 运行它后会出现一个有着 `>>>` 提示的新窗口。 在此之后，如果调用 `exit()` 函数或按 `Ctrl-Z` 组合键后窗口将会消失。 Windows 会在这个窗口中运行一个“python”命令，并且在你终止解释器的时候关闭它。

现在我们知道 `py` 命令已经被识别，可以输入Python脚本了。 你需要提供Python脚本的绝对路径或相对路径。 假设Python脚本位于桌面上并命名为 `hello.py`，并且命令提示符在用户主目录打开，那么可以看到类似于这样的东西:

    C:\Users\YourName>

那么现在可以让``py``命令执行你的脚本，只需要输入``py`` 和脚本路径:

    C:\Users\YourName> py Desktop\hello.py
    hello

## How do I make Python scripts executable?

On Windows, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (`D:\Program Files\Python\python.exe "%1" %*`). This is enough to make scripts executable from the command prompt as 'foo.py'. If you'd rather be able to execute the script by simple typing 'foo' with no extension you need to add .py to the PATHEXT environment variable.

## Why does Python sometimes take so long to start?

Usually Python starts very quickly on Windows, but occasionally there are bug reports that Python suddenly begins to take a long time to start up. This is made even more puzzling because Python will work fine on other Windows systems which appear to be configured identically.

The problem may be caused by a misconfiguration of virus checking software on the problem machine. Some virus scanners have been known to introduce startup overhead of two orders of magnitude when the scanner is configured to monitor all reads from the filesystem. Try checking the configuration of virus scanning software on your systems to ensure that they are indeed configured identically. McAfee, when configured to scan all file system read activity, is a particular offender.

## How do I make an executable from a Python script?

See cx_Freeze for a distutils extension that allows you to create console and GUI executables from Python code. py2exe, the most popular extension for building Python 2.x-based executables, does not yet support Python 3 but a version that does is in development.

## Is a `*.pyd` file the same as a DLL?

Yes, .pyd files are dll's, but there are a few differences. If you have a DLL named `foo.pyd`, then it must have a function `PyInit_foo()`. You can then write Python "import foo", and Python will search for foo.pyd (as well as foo.py, foo.pyc) and if it finds it, will attempt to call `PyInit_foo()` to initialize it. You do not link your .exe with foo.lib, as that would cause Windows to require the DLL to be present.

Note that the search path for foo.pyd is PYTHONPATH, not the same as the path that Windows uses to search for foo.dll. Also, foo.pyd need not be present to run your program, whereas if you linked your program with a dll, the dll is required. Of course, foo.pyd is required if you want to say `import foo`. In a DLL, linkage is declared in the source code with `__declspec(dllexport)`. In a .pyd, linkage is defined in a list of available functions.

## How can I embed Python into a Windows application?

Embedding the Python interpreter in a Windows app can be summarized as follows:

1. Do _not_ build Python into your .exe file directly. On Windows, Python must be a DLL to handle importing modules that are themselves DLL's. (This is the first key undocumented fact.) Instead, link to `pythonNN.dll`; it is typically installed in `C:\Windows\System`. NN is the Python version, a number such as "33" for Python 3.3.

   You can link to Python in two different ways. Load-time linking means linking against `pythonNN.lib`, while run-time linking means linking against `pythonNN.dll`. (General note: `pythonNN.lib` is the so-called "import lib" corresponding to `pythonNN.dll`. It merely defines symbols for the linker.)

   Run-time linking greatly simplifies link options; everything happens at run time. Your code must load `pythonNN.dll` using the Windows `LoadLibraryEx()` routine. The code must also use access routines and data in `pythonNN.dll` (that is, Python's C API's) using pointers obtained by the Windows `GetProcAddress()` routine. Macros can make using these pointers transparent to any C code that calls routines in Python's C API.

   Borland note: convert `pythonNN.lib` to OMF format using Coff2Omf.exe first.

2. If you use SWIG, it is easy to create a Python "extension module" that will make the app's data and methods available to Python. SWIG will handle just about all the grungy details for you. The result is C code that you link into your .exe file (!) You do _not_ have to create a DLL file, and this also simplifies linking.

3. SWIG will create an init function (a C function) whose name depends on the name of the extension module. For example, if the name of the module is leo, the init function will be called initleo(). If you use SWIG shadow classes, as you should, the init function will be called initleoc(). This initializes a mostly hidden helper class used by the shadow class.

   The reason you can link the C code in step 2 into your .exe file is that calling the initialization function is equivalent to importing the module into Python! (This is the second key undocumented fact.)

4. In short, you can use the following code to initialize the Python interpreter with your extension module.

       #include "python.h"
       ...
       Py_Initialize();  // Initialize Python.
       initmyAppc();  // Initialize (import) the helper class.
       PyRun_SimpleString("import myApp");  // Import the shadow class.

5. There are two problems with Python's C API which will become apparent if you use a compiler other than MSVC, the compiler used to build pythonNN.dll.

   Problem 1: The so-called "Very High Level" functions that take FILE * arguments will not work in a multi-compiler environment because each compiler's notion of a struct FILE will be different. From an implementation standpoint these are very _low_ level functions.

   Problem 2: SWIG generates the following code when generating wrappers to void functions:

       Py_INCREF(Py_None);
       _resultobj = Py_None;
       return _resultobj;

   Alas, Py_None is a macro that expands to a reference to a complex data structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will fail in a mult-compiler environment. Replace such code by:

       return Py_BuildValue("");

   It may be possible to use SWIG's `%typemap` command to make the change automatically, though I have not been able to get this to work (I'm a complete SWIG newbie).

6. Using a Python shell script to put up a Python interpreter window from inside your Windows app is not a good idea; the resulting window will be independent of your app's windowing system. Rather, you (or the wxPythonWindow class) should create a "native" interpreter window. It is easy to connect that window to the Python interpreter. You can redirect Python's i/o to _any_ object that supports read and write, so all you need is a Python object (defined in your extension module) that contains read() and write() methods.

## How do I keep editors from inserting tabs into my Python source?

The FAQ does not recommend using tabs, and the Python style guide, PEP 8, recommends 4 spaces for distributed Python code; this is also the Emacs python-mode default.

Under any editor, mixing tabs and spaces is a bad idea. MSVC is no different in this respect, and is easily configured to use spaces: Take Tools ‣ Options ‣ Tabs, and for file type "Default" set "Tab size" and "Indent size" to 4, and select the "Insert spaces" radio button.

Python raises `IndentationError` or `TabError` if mixed tabs and spaces are causing problems in leading whitespace. You may also run the `tabnanny` module to check a directory tree in batch mode.

## How do I check for a keypress without blocking?

Use the msvcrt module. This is a standard Windows-specific extension module. It defines a function `kbhit()` which checks whether a keyboard hit is present, and `getch()` which gets one character without echoing it.