标签归档:windows-7

Cython:“严重错误:numpy / arrayobject.h:没有此类文件或目录”

问题:Cython:“严重错误:numpy / arrayobject.h:没有此类文件或目录”

我试图加快答案在这里使用用Cython。我尝试编译代码(在完成此处cygwinccompiler.py介绍的hack 之后),但出现错误。谁能告诉我我的代码是否有问题,或者Cython有点神秘?fatal error: numpy/arrayobject.h: No such file or directory...compilation terminated

下面是我的代码。

import numpy as np
import scipy as sp
cimport numpy as np
cimport cython

cdef inline np.ndarray[np.int, ndim=1] fbincount(np.ndarray[np.int_t, ndim=1] x):
    cdef int m = np.amax(x)+1
    cdef int n = x.size
    cdef unsigned int i
    cdef np.ndarray[np.int_t, ndim=1] c = np.zeros(m, dtype=np.int)

    for i in xrange(n):
        c[<unsigned int>x[i]] += 1

    return c

cdef packed struct Point:
    np.float64_t f0, f1

@cython.boundscheck(False)
def sparsemaker(np.ndarray[np.float_t, ndim=2] X not None,
                np.ndarray[np.float_t, ndim=2] Y not None,
                np.ndarray[np.float_t, ndim=2] Z not None):

    cdef np.ndarray[np.float64_t, ndim=1] counts, factor
    cdef np.ndarray[np.int_t, ndim=1] row, col, repeats
    cdef np.ndarray[Point] indices

    cdef int x_, y_

    _, row = np.unique(X, return_inverse=True); x_ = _.size
    _, col = np.unique(Y, return_inverse=True); y_ = _.size
    indices = np.rec.fromarrays([row,col])
    _, repeats = np.unique(indices, return_inverse=True)
    counts = 1. / fbincount(repeats)
    Z.flat *= counts.take(repeats)

    return sp.sparse.csr_matrix((Z.flat,(row,col)), shape=(x_, y_)).toarray()

I’m trying to speed up the answer here using Cython. I try to compile the code (after doing the cygwinccompiler.py hack explained here), but get a fatal error: numpy/arrayobject.h: No such file or directory...compilation terminated error. Can anyone tell me if it’s a problem with my code, or some esoteric subtlety with Cython?

Below is my code.

import numpy as np
import scipy as sp
cimport numpy as np
cimport cython

cdef inline np.ndarray[np.int, ndim=1] fbincount(np.ndarray[np.int_t, ndim=1] x):
    cdef int m = np.amax(x)+1
    cdef int n = x.size
    cdef unsigned int i
    cdef np.ndarray[np.int_t, ndim=1] c = np.zeros(m, dtype=np.int)

    for i in xrange(n):
        c[<unsigned int>x[i]] += 1

    return c

cdef packed struct Point:
    np.float64_t f0, f1

@cython.boundscheck(False)
def sparsemaker(np.ndarray[np.float_t, ndim=2] X not None,
                np.ndarray[np.float_t, ndim=2] Y not None,
                np.ndarray[np.float_t, ndim=2] Z not None):

    cdef np.ndarray[np.float64_t, ndim=1] counts, factor
    cdef np.ndarray[np.int_t, ndim=1] row, col, repeats
    cdef np.ndarray[Point] indices

    cdef int x_, y_

    _, row = np.unique(X, return_inverse=True); x_ = _.size
    _, col = np.unique(Y, return_inverse=True); y_ = _.size
    indices = np.rec.fromarrays([row,col])
    _, repeats = np.unique(indices, return_inverse=True)
    counts = 1. / fbincount(repeats)
    Z.flat *= counts.take(repeats)

    return sp.sparse.csr_matrix((Z.flat,(row,col)), shape=(x_, y_)).toarray()

回答 0

在你里面setup.pyExtension应该有论据include_dirs=[numpy.get_include()]

另外,您np.import_array()的代码中缺少您。

示例setup.py:

from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy

setup(
    ext_modules=[
        Extension("my_module", ["my_module.c"],
                  include_dirs=[numpy.get_include()]),
    ],
)

# Or, if you use cythonize() to make the ext_modules list,
# include_dirs can be passed to setup()

setup(
    ext_modules=cythonize("my_module.pyx"),
    include_dirs=[numpy.get_include()]
)    

In your setup.py, the Extension should have the argument include_dirs=[numpy.get_include()].

Also, you are missing np.import_array() in your code.

Example setup.py:

from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy

setup(
    ext_modules=[
        Extension("my_module", ["my_module.c"],
                  include_dirs=[numpy.get_include()]),
    ],
)

# Or, if you use cythonize() to make the ext_modules list,
# include_dirs can be passed to setup()

setup(
    ext_modules=cythonize("my_module.pyx"),
    include_dirs=[numpy.get_include()]
)    

回答 1

对于像您这样的单文件项目,另一种选择是使用pyximportsetup.py如果使用IPython,则无需创建… …甚至无需打开命令行…都非常方便。您可以尝试在IPython或普通的Python脚本中运行以下命令:

import numpy
import pyximport
pyximport.install(setup_args={"script_args":["--compiler=mingw32"],
                              "include_dirs":numpy.get_include()},
                  reload_support=True)

import my_pyx_module

print my_pyx_module.some_function(...)
...

当然,您可能需要编辑编译器。这使得导入和重新加载对.pyx文件的作用与对文件的作用相同.py

资料来源:http : //wiki.cython.org/InstallingOnWindows

For a one-file project like yours, another alternative is to use pyximport. You don’t need to create a setup.py … you don’t need to even open a command line if you use IPython … it’s all very convenient. In your case, try running these commands in IPython or in a normal Python script:

import numpy
import pyximport
pyximport.install(setup_args={"script_args":["--compiler=mingw32"],
                              "include_dirs":numpy.get_include()},
                  reload_support=True)

import my_pyx_module

print my_pyx_module.some_function(...)
...

You may need to edit the compiler of course. This makes import and reload work the same for .pyx files as they work for .py files.

Source: http://wiki.cython.org/InstallingOnWindows


回答 2

该错误意味着在编译过程中找不到numpy头文件。

尝试这样做export CFLAGS=-I/usr/lib/python2.7/site-packages/numpy/core/include/,然后进行编译。这是几个不同软件包的问题。在ArchLinux中,存在针对同一问题的错误: https //bugs.archlinux.org/task/22326

The error means that a numpy header file isn’t being found during compilation.

Try doing export CFLAGS=-I/usr/lib/python2.7/site-packages/numpy/core/include/, and then compiling. This is a problem with a few different packages. There’s a bug filed in ArchLinux for the same issue: https://bugs.archlinux.org/task/22326


回答 3

简单的答案

一种更简单的方法是将路径添加到文件中distutils.cfg。默认情况下,它代表Windows 7的路径C:\Python27\Lib\distutils\。您只需声明以下内容即可解决:

[build_ext]
include_dirs= C:\Python27\Lib\site-packages\numpy\core\include

整个配置文件

为了给您一个示例,配置文件的外观,我的整个文件显示为:

[build]
compiler = mingw32

[build_ext]
include_dirs= C:\Python27\Lib\site-packages\numpy\core\include
compiler = mingw32

Simple answer

A way simpler way is to add the path to your file distutils.cfg. It’s path behalf of Windows 7 is by default C:\Python27\Lib\distutils\. You just assert the following contents and it should work out:

[build_ext]
include_dirs= C:\Python27\Lib\site-packages\numpy\core\include

Entire config file

To give you an example how the config file could look like, my entire file reads:

[build]
compiler = mingw32

[build_ext]
include_dirs= C:\Python27\Lib\site-packages\numpy\core\include
compiler = mingw32

回答 4

它应该能够在此处cythonize()提到的函数中执行此操作,但是由于存在已知问题,因此它不起作用

It should be able to do it within cythonize() function as mentioned here, but it doesn’t work beacuse there is a known issue


回答 5

如果您懒得编写设置文件并弄清楚包含目录的路径,请尝试cyper。它可以编译您的Cython代码并进行设置include_dirs自动为Numpy。

将您的代码加载到字符串中,然后简单地运行cymodule = cyper.inline(code_string),然后您的函数cymodule.sparsemaker即刻可用。像这样

code = open(your_pyx_file).read()
cymodule = cyper.inline(code)

cymodule.sparsemaker(...)
# do what you want with your function

您可以通过安装cyper pip install cyper

If you are too lazy to write setup files and figure out the path for include directories, try cyper. It can compile your Cython code and set include_dirs for Numpy automatically.

Load your code into a string, then simply run cymodule = cyper.inline(code_string), then your function is available as cymodule.sparsemaker instantaneously. Something like this

code = open(your_pyx_file).read()
cymodule = cyper.inline(code)

cymodule.sparsemaker(...)
# do what you want with your function

You can install cyper via pip install cyper.


如何在Windows 7的命令提示符中运行Python程序?

问题:如何在Windows 7的命令提示符中运行Python程序?

我试图弄清楚如何在Windows 7上使用命令提示符运行Python程序。(我现在应该已经弄清楚了……)

当我在命令提示符下键入“ python”时,出现以下错误:

无法将“ python”识别为内部或外部命令,可操作程序或批处理文件。

我在寻求帮助时发现的第一个地方是该网站:http : //docs.python.org/faq/windows.html#how-do-i-run-a-python-program-under-windows

它虽然有所帮助,但是该教程是针对Windows 2000及更早版本编写的,因此对我的Windows 7计算机几乎没有帮助。我尝试了以下操作:

对于Windows的较早版本,最简单的方法是编辑C:\ AUTOEXEC.BAT>文件。您可能想在AUTOEXEC.BAT中添加以下内容:

该文件在我的机器上不存在(除非我弄错了)。

接下来,我尝试了此操作:(这里:如何运行Python程序?

将Python放在您的路径上

视窗

为了运行程序,您的操作系统会在各个地方出现,并尝试将您键入的程序/命令的名称与过程中的某些程序进行匹配。

在Windows中:

控制面板>系统>高级> |环境变量| >系统变量->路径

这需要包括:C:\ Python26; (或同等学历)。如果将其放在最前面,它将是第一位。您也可以在末尾添加它,这可能会更好。

然后重新启动提示,并尝试键入“ python”。如果一切正常,您应该收到一个“ >>>”提示。

对于Windows 7来说,这已经足够相关了,我进入了系统变量。我添加了一个值“ C:\ Python27”的变量“ python”

即使重新启动计算机后,我仍然会收到错误消息。

有人知道怎么修这个东西吗?

I’m trying to figure out how to run Python programs with the Command Prompt on Windows 7. (I should have figured this out by now…)

When I typed “python” into the command prompt, I got the following error:

‘python’ is not recognized as an internal or external command, operable program or batch file.

The first place I found when looking for help was this site: http://docs.python.org/faq/windows.html#how-do-i-run-a-python-program-under-windows.

It was somewhat helpful, but the tutorial was written for Windows 2000 and older, so it was minimally helpful for my Windows 7 machine. I attempted the following:

For older versions of Windows the easiest way to do this is to edit the C:\AUTOEXEC.BAT >file. You would want to add a line like the following to AUTOEXEC.BAT:

This file did not exist on my machine (unless I’m mistaken).

Next, I tried this: (here: How do I run a Python program?)

Putting Python In Your Path

Windows

In order to run programs, your operating system looks in various places, and tries to match the name of the program / command you typed with some programs along the way.

In windows:

control panel > system > advanced > |Environmental Variables| > system variables -> Path

this needs to include: C:\Python26; (or equivalent). If you put it at the front, it will be the first place looked. You can also add it at the end, which is possibly saner.

Then restart your prompt, and try typing ‘python’. If it all worked, you should get a “>>>” prompt.

This was relevant enough for Windows 7, and I made my way to the System Variables. I added a variable “python” with the value “C:\Python27”

I continued to get the error, even after restarting my computer.

Anyone know how to fix this?


回答 0

您需要向C:\Python27系统中添加PATH变量,而不是名为“ python”的新变量。

找到系统PATH环境变量,并在;其后附加一个(是定界符)和包含python.exe的目录的路径(例如C:\Python27)。请参阅下面的确切步骤。

PATH环境变量列出Windows(和cmd.exe)在给定命令名称(例如“ python”)时将检查的所有位置(它还将PATHEXT变量用于尝试的可执行文件扩展名列表)。它在PATH上找到的第一个具有该名称的可执行文件就是启动的文件。

请注意,更改此变量后,无需重新启动Windows,只有的新实例cmd.exe将具有更新的PATH。您可以set PATH在命令提示符下键入以查看当前值。


在Windows 7+上将Python添加到路径的确切步骤:

  1. 计算机->系统属性(或Win+Break)->高级系统设置
  2. 单击Environment variables...按钮(在“高级”选项卡中)
  3. 编辑路径和附加;C:\Python27到最后(代替你的Python版本)
  4. 单击确定。请注意,对PATH的更改仅反映在更改发生打开的命令提示符中。

You need to add C:\Python27 to your system PATH variable, not a new variable named “python”.

Find the system PATH environment variable, and append to it a ; (which is the delimiter) and the path to the directory containing python.exe (e.g. C:\Python27). See below for exact steps.

The PATH environment variable lists all the locations that Windows (and cmd.exe) will check when given the name of a command, e.g. “python” (it also uses the PATHEXT variable for a list of executable file extensions to try). The first executable file it finds on the PATH with that name is the one it starts.

Note that after changing this variable, there is no need to restart Windows, but only new instances of cmd.exe will have the updated PATH. You can type set PATH at the command prompt to see what the current value is.


Exact steps for adding Python to the path on Windows 7+:

  1. Computer -> System Properties (or Win+Break) -> Advanced System Settings
  2. Click the Environment variables... button (in the Advanced tab)
  3. Edit PATH and append ;C:\Python27 to the end (substitute your Python version)
  4. Click OK. Note that changes to the PATH are only reflected in command prompts opened after the change took place.

回答 1

假设您已安装Python2.7

  1. 转到开始菜单

  2. 右键单击“计算机”

  3. 选择“属性”

  4. 将会弹出一个对话框,左侧有一个链接,称为“高级系统设置”。点击它。

  5. 在“系统属性”对话框中,单击名为“环境变量”的按钮。

  6. 在“环境变量”对话框中,在“系统变量”窗口下查找“路径”。

  7. 在其末尾添加“; C:\ Python27”。分号是Windows上的路径分隔符。

  8. 单击确定,然后关闭对话框。

  9. 现在打开一个新的命令提示符,然后键入“ python”

它应该工作。

Assuming you have Python2.7 installed

  1. Goto the Start Menu

  2. Right Click “Computer”

  3. Select “Properties”

  4. A dialog should pop up with a link on the left called “Advanced system settings”. Click it.

  5. In the System Properties dialog, click the button called “Environment Variables”.

  6. In the Environment Variables dialog look for “Path” under the System Variables window.

  7. Add “;C:\Python27” to the end of it. The semicolon is the path separator on windows.

  8. Click Ok and close the dialogs.

  9. Now open up a new command prompt and type “python”

It should work.


回答 2

为了使我的Python脚本在Windows机器(WinXP和Win7)上正常运行,我花了一些心血在这里,在Web上以及在Python文档中寻找答案,并自行进行测试。因此,我只是写了一篇博客,并将其粘贴在下面,以防对他人有用。很抱歉,它很长,可以随时进行改进;我不是专家。

[ 更新:Python 3.3现在包括适用于Windows的Python启动器,可让您键入py(而不是python)来调用默认解释器,或py -2,py -3,py -2.7等。它还支持shebang行,允许脚本本身指定。对于3.3之前的版本,可以单独下载启动器。 http://docs.python.org/3/whatsnew/3.3.html ]

在Windows下方便地运行Python脚本

也许您正在创建自己的Python脚本,或者有人为您提供了一个处理数据文件的工具。假设您已获取Python脚本并将其保存到“ D:\ my scripts \ ApplyRE.py”。您想通过双击它或从任何位置在命令行中键入它来方便地运行它,并可以像这样将参数传递给它(-o表示“如果已经存在则覆盖输出文件”):

ApplyRE infile.txt outfile.txt -o

假设您还有一个数据文件“ C:\ some files \ some lexicon.txt”。最简单的选择是移动文件或脚本,使它们位于相同的位置,但这可能会造成混乱,因此,我们假定它们将保持分开。

确保Windows可以找到Python解释器

安装Python之后,请验证在命令提示符下键入python是否有效(然后键入exit()以退出Python解释器)。

C:\>python
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
C:\>

如果这不起作用,则需要在PATH环境变量中附加“; C:\ Python32”之类的内容(不带引号)。有关说明,请参见下面的PATHEXT。

将Python与.py和.pyc关联

验证双击ApplyRE.py可以运行它。(顺便说一下,它还应该带有Python徽标作为其图标,并标记为“ Python File”。)如果尚未完成,请右键单击.py文件,选择“打开方式”,选择“程序”,然后选中“始终使用…”此关联可以提高便利性,但并非绝对必要-您每次要运行脚本时都可以指定“ python”,如下所示:

D:\my scripts>python ApplyRE.py lexicon-sample.txt -o
Running... Done.

这是一个非常具体的变体,除非您需要指定其他版本的解释器,否则它是可选的。

D:\my scripts>c:\python32\python ApplyRE.py lexicon-sample.txt -o
Running... Done.

但这很痛苦。幸运的是,一旦在PATH中安装了Python,并将其与.py关联,则双击.py文件或直接将其作为命令键入应该可以正常工作。在这里,我们似乎直接在运行脚本–在脚本旁边的“我的脚本”文件夹中的示例文件上运行脚本很简单。

D:\my scripts>ApplyRE.py lexicon-sample.txt -o
Running... Done.

省略.py扩展名(编辑PATHEXT)

为了进一步减少键入,您可以告诉Windows .py(也许还有.pyc文件)是可执行的。为此,右键单击“计算机”,然后选择“属性”,“高级”,“环境变量”,“系统变量”。在现有的PATHEXT变量后面加上“; .PY; .PYC”(不带引号),或者如果您还不确定,则创建它。关闭并重新打开命令提示符。现在,您应该可以省略.py(仅供参考,如果存在,这样做将导致ApplyRE.exe或ApplyRE.bat改为运行)。

D:\my scripts>ApplyRE lexicon-sample.txt -o
Running... Done.

将脚本添加到系统PATH

如果您要经常从命令提示符下使用脚本(通过使用BAT文件这样做不太重要),则需要将脚本文件夹添加到系统PATH。(在PATHEXT旁边,您应该看到一个PATH变量;在该变量后附加“; D:\ my脚本”,不带引号。)这样,您可以针对当前位置的文件从其他位置运行脚本,如下所示:

C:\some files>ApplyRE "some lexicon.txt" "some lexicon OUT.txt" -o
Running... Done.

成功!这几乎是您简化命令行所需要做的全部工作。

直接运行而无需调整PATH

如果您是快速打字员,或者不介意为每种情况创建批处理文件,则可以指定完整路径(用于脚本或参数),而无需调整PATH。

C:\some files>"d:\my scripts\ApplyRE.py" "some lexicon.txt" "some lexicon OUT.txt" -o
Running... Done.
C:\some files>d:
D:\>cd "my scripts"
D:\my scripts>ApplyRE.py "c:\some files\some lexicon.txt" "c:\some files\some lexicon OUT.txt" -o
Running... Done.

创建快捷方式或批处理文件

如果.py与已安装的Python相关联,则可以双击ApplyRE.py来运行它,但是控制台可能会出现或消失得太快而无法读取其输出(或失败!)。要传递参数,您首先需要执行以下操作之一。(a)右键单击并创建一个快捷方式。右键单击快捷方式以编辑属性并将参数附加到Target。(b)创建一个批处理文件-具有不同名称的纯文本文件,例如ApplyRErun.bat。此选项可能更好,因为您可以要求它暂停以查看输出。这是示例BAT文件的内容,该文件的位置是从c:\ some文件定位并运行。

python "d:\my scripts\ApplyRE.py" "some lexicon.txt" "some lexicon OUT.txt" -o
pause

高级:附加到PYTHONPATH

通常这不是必需的,但是其他可能相关的环境变量是PYTHONPATH。如果我们将d:\ my脚本附加到该变量,则其他位置的其他Python脚本可以通过import语句使用这些脚本。

It has taken me some effort looking for answers here, on the web, and and in the Python documentation, and testing on my own, to finally get my Python scripts working smoothly on my Windows machines (WinXP and Win7). So, I just blogged about it and am pasting that below in case it’s useful to others. Sorry it’s long, and feel free to improve it; I’m no expert.

[UPDATE: Python 3.3 now includes the Python Launcher for Windows, which allows you to type py (rather than python) to invoke the default interpreter, or py -2, py -3, py -2.7, etc. It also supports shebang lines, allowing the script itself to specify. For versions prior to 3.3, the launcher is available as a separate download. http://docs.python.org/3/whatsnew/3.3.html ]

Running Python scripts conveniently under Windows

Maybe you’re creating your own Python scripts, or maybe someone has given you one for doing something with your data files. Say you’ve acquired a Python script and have saved it to “D:\my scripts\ApplyRE.py”. You want to run it conveniently by either double-clicking it or typing it into the command line from any location, with the option of passing parameters to it like this (-o means “overwrite the output file if it already exists”):

ApplyRE infile.txt outfile.txt -o

Say you also have a data file, “C:\some files\some lexicon.txt”. The simplest option is to move the file or the script so they’re in the same location, but that can get messy, so let’s assume that they’ll stay separate.

Making sure Windows can find the Python interpreter

After installing Python, verify that typing python into a command prompt works (and then type exit() to get back out of the Python interpreter).

C:\>python
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
C:\>

If this doesn’t work, you’ll need to append something like “;C:\Python32” (without quotes) to the PATH environment variable. See PATHEXT below for instructions.

Associating Python with .py and .pyc

Verify that double-clicking on ApplyRE.py runs it. (It should also have a Python logo as its icon and be labeled “Python File”, by the way.) If this isn’t already done, right-click on a .py file, choose Open With, Choose Program, and check “Always use…” This association improves convenience but isn’t strictly necessary–you can specify “python” every time you want to run a script, like this:

D:\my scripts>python ApplyRE.py lexicon-sample.txt -o
Running... Done.

Here’s a very specific variation, which is optional unless you need to specify a different version of the interpreter.

D:\my scripts>c:\python32\python ApplyRE.py lexicon-sample.txt -o
Running... Done.

But that’s a pain. Fortunately, once Python is installed, in the PATH, and associated with .py, then double-clicking a .py file or directly typing it as a command should work fine. Here, we seem to be running the script directly–it’s nice and simple to run it on a sample file that’s located in the “my scripts” folder along with the script.

D:\my scripts>ApplyRE.py lexicon-sample.txt -o
Running... Done.

Omitting the .py extension (editing PATHEXT)

To further reduce typing, you can tell Windows that .py (and perhaps .pyc files) are executable. To do this, right-click Computer and choose Properties, Advanced, Environment Variables, System Variables. Append “;.PY;.PYC” (without quotes) to the existing PATHEXT variable, or else create it if you’re certan it doesn’t exist yet. Close and reopen the command prompt. You should now be able to omit the .py (FYI, doing so would cause ApplyRE.exe or ApplyRE.bat to run instead, if one existed).

D:\my scripts>ApplyRE lexicon-sample.txt -o
Running... Done.

Adding scripts to the system PATH

If you’re going to use your scripts often from the command prompt (it’s less important if doing so via using BAT files), then you’ll want to add your scripts’ folder to the system PATH. (Next to PATHEXT you should see a PATH variable; append “;D:\my scripts” to it, without quotes.) This way you can run a script from some other location against the files in current location, like this:

C:\some files>ApplyRE "some lexicon.txt" "some lexicon OUT.txt" -o
Running... Done.

Success! That’s pretty much all you need to do to streamline the command-line.

Running directly without tweaking the PATH

If you’re a fast typist or don’t mind creating a batch file for each situation, you can specify full paths (for the script, or for the parameters) instead of tweaking PATH.

C:\some files>"d:\my scripts\ApplyRE.py" "some lexicon.txt" "some lexicon OUT.txt" -o
Running... Done.
C:\some files>d:
D:\>cd "my scripts"
D:\my scripts>ApplyRE.py "c:\some files\some lexicon.txt" "c:\some files\some lexicon OUT.txt" -o
Running... Done.

Creating shortcuts or batch files

If .py is associated with an installed Python, you can just double-click ApplyRE.py to run it, but the console may appear and disappear too quickly to read its output (or failure!). And to pass parameters, you’d need to first do one of the following. (a) Right-click and create a shortcut. Right-click the shortcut to edit properties and append parameters to Target. (b) Create a batch file–a plain text file with a distinct name such as ApplyRErun.bat. This option is probably better because you can ask it to pause so you can see the output. Here is a sample BAT file’s contents, written to be located and run from c:\some files .

python "d:\my scripts\ApplyRE.py" "some lexicon.txt" "some lexicon OUT.txt" -o
pause

Advanced: appending to PYTHONPATH

This usually isn’t necessary, but one other environment variable that may be relevant is PYTHONPATH. If we were to append d:\my scripts to that variable, then other Python scripts in other locations could make use of those via import statements.


回答 3

Python附带了一个脚本,该脚本负责为您设置Windows路径文件。

安装后,打开命令提示符

cmd

转到您在其中安装Python的目录

cd C:\Python27

在Tools \ Scripts中运行python和win_add2path.py脚本

python.exe Tools\Scripts\win_add2path.py

现在,您可以python在任何地方将其用作命令。

Python comes with a script that takes care of setting up the windows path file for you.

After installation, open command prompt

cmd

Go to the directory you installed Python in

cd C:\Python27

Run python and the win_add2path.py script in Tools\Scripts

python.exe Tools\Scripts\win_add2path.py

Now you can use python as a command anywhere.


回答 4

您必须将python路径放入PATH变量中。

在系统变量部分,您应该具有用户变量和系统变量。搜索PATH变量并编辑其值,并在末尾添加;C:\python27

的作用;是告诉变量向该值添加新路径,其余的只是告诉该路径。

另一方面,您可以;%python%用来添加创建的变量。

You have to put the python path in the PATH variable.

In the System Variables section, you should have User Variables and System Variables. Search for the PATH variable and edit its value, adding at the end ;C:\python27.

The ; is to tell the variable to add a new path to this value, and the rest, is just to tell which path that is.

On the other hand, you can use ;%python% to add the variable you created.


回答 5

您无需向系统变量中添加任何变量。您采用现有的“ Path”系统变量,并在其后添加分号进行修改,然后使用c:\​​ Python27

You don’t add any variables to the System Variables. You take the existing ‘Path’ system variable, and modify it by adding a semi-colon after, then c:\Python27


回答 6

因此,经过30分钟的研发,我意识到在环境变量中设置PATH之后

“ C:\ Python / 27;”

刚重启

现在打开cmd:

C:> cd Python27 C:\ Python27> python.exe

使用扩展名为python.exe

替代选项是:

如果该软件安装正确,可直接运行Python程序,则您的命令行屏幕将自动显示而无需cmd。

谢谢。

So after 30 min of R&D i realized that after setup the PATH at environment variable

i.e.

” C:\Python/27; ”

just restart

now open cmd :

C:> cd Python27 C:\ Python27> python.exe

USE python.exe with extension

alternative option is :

if the software is installed properly directly run Python program, your command line screen will automatically appear without cmd.

Thanks.


回答 7

  • 转到开始菜单

  • 右键单击“计算机”

  • 选择“属性”

  • 将会弹出一个对话框,左侧有一个链接,称为“高级系统设置”。点击它。

  • 在“系统属性”对话框中,单击名为“环境变量”的按钮。

  • 在“环境变量”对话框中,在“系统变量”窗口下查找“路径”。

  • 在其末尾添加“; C:\ Python27”。分号是Windows上的路径分隔符。

  • 单击确定,然后关闭对话框。

  • 现在打开一个新的命令提示符,然后键入“ python”,或者如果错误提示键入“ py”而不是“ python”

  • Go to the Start Menu

  • Right Click “Computer”

  • Select “Properties”

  • A dialog should pop up with a link on the left called “Advanced system settings”. Click it.

  • In the System Properties dialog, click the button called “Environment Variables”.

  • In the Environment Variables dialog look for “Path” under the System Variables window.

  • Add “;C:\Python27” to the end of it. The semicolon is the path separator on windows.

  • Click Ok and close the dialogs.

  • Now open up a new command prompt and type “python” or if it says error type “py” instead of “python”


回答 8

即使经过许多帖子,也要花几个小时才能解决问题。这是用简单的语言编写的详细方法,可以在Windows中通过命令行运行python。

1.从python.org下载可执行文件
选择最新版本并下载Windows可执行安装程序。执行下载的文件并完成安装。

2.确保文件已下载到某些管理员文件夹中

  1. 搜索Python应用程序的文件位置。
  2. 右键单击.exe文件,然后导航至其属性。检查其格式是否为“ C:\ Users ….”。如果为“否”,则可以进行第3步。否则,请克隆Python37或您下载到以下位置之一的任何版本:“ C:\”,“ C:\ Program Files”,“ C:\ Program Files” (x86)”。

3.更新系统PATH变量 这是最关键的步骤,有两种方法可以做到这一点:-(最好遵循第二步)

1.手动
-在搜索栏中搜索“编辑系统环境变量”。(WINDOWS 10)
-在“系统属性”对话框中,导航到“环境变量”。
-在“环境变量”对话框中,在“系统变量”窗口下查找“路径”。(#确保单击名为System Variables而不是用户变量的底部窗口下
的Path )-通过添加Python37 / PythonXX文件夹的位置来编辑Path Variable。我添加了以下行:-
“; C:\ Program Files(x86)\ Python37; C:\ Program Files(x86)\ Python37 \ Scripts”
-单击“确定”并关闭对话框。

2.脚本
-打开命令提示符,并使用cd命令导航到Python37 / XX文件夹。
-编写以下语句:-
“ python.exe工具\脚本\ win_add2path.py”

现在,您可以在命令提示符下使用python :)
1.使用Shell
在cmd中键入python并使用它。
2.执行一个.py文件
键入python filename.py来执行它。

Even after going through many posts, it took several hours to figure out the problem. Here is the detailed approach written in simple language to run python via command line in windows.

1. Download executable file from python.org
Choose the latest version and download Windows-executable installer. Execute the downloaded file and let installation complete.

2. Ensure the file is downloaded in some administrator folder

  1. Search file location of Python application.
  2. Right click on the .exe file and navigate to its properties. Check if it is of the form, “C:\Users….”. If NO, you are good to go and jump to step 3. Otherwise, clone the Python37 or whatever version you downloaded to one of these locations, “C:\”, “C:\Program Files”, “C:\Program Files (x86)”.

3. Update the system PATH variable This is the most crucial step and there are two ways to do this:- (Follow the second one preferably)

1. MANUALLY
– Search for ‘Edit the system Environment Variables’ in the search bar.(WINDOWS 10)
– In the System Properties dialog, navigate to “Environment Variables”.
– In the Environment Variables dialog look for “Path” under the System Variables window. (# Ensure to click on Path under bottom window named System Variables and not under user variables)
– Edit the Path Variable by adding location of Python37/ PythonXX folder. I added following line:-
” ;C:\Program Files (x86)\Python37;C:\Program Files (x86)\Python37\Scripts “
– Click Ok and close the dialogs.

2. SCRIPTED
– Open the command prompt and navigate to Python37/XX folder using cd command.
– Write the following statement:-
“python.exe Tools\Scripts\win_add2path.py”

You can now use python in the command prompt:)
1. Using Shell
Type python in cmd and use it.
2. Executing a .py file
Type python filename.py to execute it.


回答 9

首先确保您输入路径环境变量

C:\ path%path%; C:\ Python27按Enter

C:\ Python27> python file_name按Enter

first make sure u enter the path environmental variable

C:\ path %path%;C:\Python27 press Enter

C:\Python27>python file_name press Enter


回答 10

只想提一下,当您这样做时:

cd C:\Python27
python Tools\Scripts\win_add2path.py

管理员用户变量中的PATH变量已更改。

但是您也可以按照其他人的回答打开:

系统->高级系统设置->高级->环境变量,

并在“ 系统变量 ”中修改/添加变量路径,;C:\Python27并在其末尾添加。

Just want to mention, when you do:

cd C:\Python27
python Tools\Scripts\win_add2path.py

The PATH variable in “user variables for administrator” is changed.

But you can also follow the others’ answer to open:

System -> advanced system settings -> advanced -> Environment Variables,

and modify/add the variable Path in “System Variables“, add ;C:\Python27 at the end of it.


回答 11

在powershell中输入以下内容:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

关闭并打开Powershell,然后重试。这应该可以解决您的问题。

in powershell enter the following:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

close and open the powershell and try again. this should solve your problem.


回答 12

您需要编辑名为的环境变量PATH,并将其添加;c:\python27到末尾。分号将一个路径名与另一个路径名分隔(您已经在其中包含了几项内容PATH)。

或者,您可以输入

c:\python27\python

在命令提示符下,根本不需要修改任何环境变量。

You need to edit the environment variable named PATH, and add ;c:\python27 to the end of that. The semicolon separates one pathname from another (you will already have several things in your PATH).

Alternately, you can just type

c:\python27\python

at the command prompt without having to modify any environment variables at all.


回答 13

在Windows上,您使用C:\Python27\python.exe而不是python

如果添加C:\Python27到路径中,则可以将其缩短为just python.exe,但是您不需要这样做。

On Windows you use C:\Python27\python.exe instead of python.

If you add C:\Python27 to your path, you can shorten it to just python.exe, but you do not need to do this.


回答 14

还要修改PATH变量并追加,;%python%否则找不到可执行文件。

Modify the PATH variable too and append ;%python% otherwise the executable can not be found.


回答 15

首先使用此URL将Python安装到Windows中 ,然后将path变量添加为

c:\python27

First install the Python into your windows by using this url and then add path variable as

c:\python27

回答 16

在Windows 7中使用以下PATH:

C:\Python27;C:\Python27\Lib\site-packages\;C:\Python27\Scripts\;

Use this PATH in Windows 7:

C:\Python27;C:\Python27\Lib\site-packages\;C:\Python27\Scripts\;

回答 17

即使我在环境变量中添加了路径,我也发现了同样的问题。最后,我将我的“ C:\ Python27”放在环境变量“ PATH”的FRONT部分中,然后重新启动cmd,它可以正常工作!!!希望对您有所帮助。

I also found the same problem even though i’ve added the path in the environment variable. Finally, I put my “C:\Python27” in the FRONT part of the “PATH” in environment variable and after restarting the cmd, it works!!! I hope this can help.


回答 18

对于Windows 10和Python 3.5.1用户:

在Windows 10上安装Python时,请不要忘记在单击“安装”之前检查“添加到cmd提示”选项。这将有助于轻松地从cmd访问python。

如果未选中该选项,请在cmd中使用“设置路径”以查看它是否可作为可执行文件使用。如果不是,请导航至开始>>控制面板>>系统和安全>>系统>>高级系统设置>>高级>>环境变量。>>从系统变量中选择PATH并进行编辑。然后在新行中复制“ C:\ Python35 \ cmd”。此后,请按照相同步骤将.PY添加到PATHEXT。

还请检查开始>>控制面板>>系统和安全>>系统>>高级系统设置>>高级>>环境变量.. >>用户名中的用户变量>> PATH是否包含这两行-“ C:\ Users \ Username \ AppData \ Local \ Programs \ Python \ Python35-32 \ Scripts \“和” C:\ Users \ Username \ AppData \ Local \ Programs \ Python \ Python35-32 \“。否则,请手动添加它们。

参考:https : //docs.python.org/3/using/windows.html

For Windows 10 & Python 3.5.1 users:

While installing Python on Windows 10, please don’t forget to check the “Add to cmd prompt” option before hitting the “Install”. This would help in easily access python from cmd.

If the option was not checked, then please use Set Path in cmd to see if it is available as executables or not. If not, Navigate to Start >> Control Panel >> System and Security >> System >> Advanced System Settings >> Advanced >> Environment Variables.. >> Select PATH from System Variables and Edit it. Then copy “C:\Python35\cmd” in the new line. After this please add .PY to PATHEXT in the same procedure.

Also please check if Start >> Control Panel >> System and Security >> System >> Advanced System Settings >> Advanced >> Environment Variables.. >> User variables from Username >> PATH is containing these two lines – “C:\Users\Username\AppData\Local\Programs\Python\Python35-32\Scripts\” & “C:\Users\Username\AppData\Local\Programs\Python\Python35-32\”. Else please add them manually.

Ref: https://docs.python.org/3/using/windows.html


回答 19

转到“开始”菜单,右键单击“计算机”,然后选择“属性”。随即会弹出一个对话框,其中左侧的链接为“高级系统设置”。点击它。在“系统属性”对话框中,单击名为“环境变量”的按钮。在“环境变量”对话框中,在“系统变量”窗口下查找“路径”。在其末尾添加“; C:\ Python27”。分号是Windows上的路径分隔符。单击确定,然后关闭对话框。现在打开一个新的命令提示符,然后键入“ python”

如果问题仍然存在,请在命令提示符下键入“ py”而不是“ python”。可能有帮助!!!!

Goto the Start Menu Right Click “Computer” Select “Properties” A dialog should pop up with a link on the left called “Advanced system settings”. Click it. In the System Properties dialog, click the button called “Environment Variables”. In the Environment Variables dialog look for “Path” under the System Variables window. Add “;C:\Python27” to the end of it. The semicolon is the path separator on windows. Click Ok and close the dialogs. Now open up a new command prompt and type “python”

If still the problem persists then type “py” instead of “python” in command prompt. might help!!!!


回答 20

按开始按钮,然后键入cmd。-请注意,您将需要以“管理员”身份运行命令提示符。

setx -m path "%path%;C:\Python27"然后按Enter。

[这里-m为所有用户提供访问权限,在Python2727中为2.7版]

%path%;将防止原始值被破坏。C:\ Python27将被追加到当前Path值。

就是这样,您完成了。

press start button then type cmd. – Note you will need to run the command prompt as ‘Adminstrator’.

write setx -m path "%path%;C:\Python27" then press enter.

[here -m for giving accessing permission to all users and in Python27 27 is version 2.7]

%path%; will prevent the original value from destroying. C:\Python27 will be appended to the current Path value.

that’s it,you are done.


回答 21

您执行的所有步骤都是正确的,除了一个步骤,而是创建一个单独的变量,请尝试以下步骤。

  1. 搜索python.exe文件,找到父文件夹。
  2. 复制文件夹路径,例如python安装文件所在的路径
  3. 现在转到控制面板-系统高级设置-环境变量
  4. 查找路径变量将复制的文件夹路径粘贴到此处并添加;
  5. 现在所有已设置为执行的goto cmd类型,python您必须看到版本详细信息

All the steps you have performed are correct, except one step, instead creating one separate variable, try below steps.

  1. Search for python.exe file, find the parent folder.
  2. Copy the folder path like on which python installation files resides
  3. Now go to the control panel-system-advanced settings-environment variables
  4. Find Path variable paste the copied folder path here and add ;
  5. Now all set for the execution goto cmd type python you must see the version details

回答 22

对于Windows 8,只需键入“ py”。

For windows 8, just type “py”.