标签归档:windows

为什么在文件路径中出现Unicode转义的SyntaxError?

问题:为什么在文件路径中出现Unicode转义的SyntaxError?

我要访问的文件夹称为python,位于我的桌面上。

尝试获取以下错误

>>> os.chdir('C:\Users\expoperialed\Desktop\Python')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

The folder I want to get to is called python and is on my desktop.

I get the following error when I try to get to it

>>> os.chdir('C:\Users\expoperialed\Desktop\Python')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

回答 0

您需要使用原始字符串,将斜杠加倍或使用正斜杠:

r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'

在常规python字符串中,\U字符组合表示扩展的Unicode代码点转义。

对于任何已识别的转义序列,例如\at\x,您可以遇到许多其他问题。

You need to use a raw string, double your slashes or use forward slashes instead:

r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'

In regular python strings, the \U character combination signals a extended Unicode codepoint escape.

You can hit any number of other issues, for any of the recognised escape sequences, such as \a or \t or \x, etc.


回答 1

C:\\Users\\expoperialed\\Desktop\\Python 这种语法对我有用。

C:\\Users\\expoperialed\\Desktop\\Python This syntax worked for me.


回答 2

这通常发生在Python 3中。常见的原因之一是在指定文件路径时,您需要使用“ \\”而不是“ \”。如:

filePath = "C:\\User\\Desktop\\myFile"

对于Python 2,只需使用“ \”即可。

This usually happens in Python 3. One of the common reasons would be that while specifying your file path you need “\\” instead of “\”. As in:

filePath = "C:\\User\\Desktop\\myFile"

For Python 2, just using “\” would work.


回答 3

f = open('C:\\Users\\Pooja\\Desktop\\trolldata.csv')

对于Python 3及更高版本的Python程序,请使用“ \\”。错误将得到解决。

f = open('C:\\Users\\Pooja\\Desktop\\trolldata.csv')

Use ‘\\’ for python program in Python version 3 and above.. Error will be resolved..


回答 4

所有这三种语法都能很好地工作。

另一种方法是先写

path = r’C:\ user \ ……….’(无论您使用什么路径)

然后将其传递给os.chdir(path)

All the three syntax work very well.

Another way is to first write

path = r’C:\user\……………….’ (whatever is the path for you)

and then passing it to os.chdir(path)


回答 5

用这个

os.chdir('C:/Users\expoperialed\Desktop\Python')

Use this

os.chdir('C:/Users\expoperialed\Desktop\Python')

回答 6

我有同样的错误。基本上,我怀疑路径在“ C:\”之后不能以“ U”或“ User”开头。通过将要从python访问的文件放在“ c:\”路径下,将目录更改为“ c:\ file_name.png”。

在您的情况下,如果必须访问“ python”文件夹,则可能重新安装python,然后将安装路径更改为“ c:\ python”。否则,只需避免路径中出现“ … \ User …”,然后将项目放在C:下。

I had the same error. Basically, I suspect that the path cannot start either with “U” or “User” after “C:\”. I changed my directory to “c:\file_name.png” by putting the file that I want to access from python right under the ‘c:\’ path.

In your case, if you have to access the “python” folder, perhaps reinstall the python, and change the installation path to something like “c:\python”. Otherwise, just avoid the “…\User…” in your path, and put your project under C:.


在Windows中将MySQL与Python集成

问题:在Windows中将MySQL与Python集成

我发现在Windows系统中很难将MySQL与Python结合使用。

我目前正在使用Python 2.6。我试图使用提供的安装脚本来编译MySQL-python-1.2.3b1(应该适用于Python 2.6吗?)源代码。安装脚本将运行,并且不会报告任何错误,但不会生成_mysql模块。

我也尝试过为Python 2.5设置MySQL,但没有成功。使用2.5的问题是Python 2.5是使用Visual Studio 2003编译的(我使用提供的二进制文件安装了它)。我在Windows系统上安装了Visual Studio 2005。因此setuptools无法生成_mysql模块。

有什么帮助吗?

I am finding it difficult to use MySQL with Python in my windows system.

I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn’t report any error but it doesn’t generate _mysql module.

I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.

Any help ?


回答 0

python-mysqldb的下载页面。该页面包含适用于Python 2.5、2.6和2.7的32位和64位版本的二进制文件。

也有关于消除弃用警告的讨论

更新:这是一个旧的答案。目前,我建议使用PyMySQL。它是纯python,因此它同样支持所有操作系统,几乎是mysqldb的直接替代品,并且还可以与python 3一起使用。最好的安装方法是使用pip。您可以从这里安装它(更多说明在此处),然后运行:

pip install pymysql

Download page for python-mysqldb. The page includes binaries for 32 and 64 bit versions of for Python 2.5, 2.6 and 2.7.

There’s also discussion on getting rid of the deprecation warning.

UPDATE: This is an old answer. Currently, I would recommend using PyMySQL. It’s pure python, so it supports all OSes equally, it’s almost a drop-in replacement for mysqldb, and it also works with python 3. The best way to install it is using pip. You can install it from here (more instructions here), and then run:

pip install pymysql

回答 1

这可能听起来像您的爷爷给我的建议,但是这里的所有答案都没有提到最好的方法:去安装ActivePython而不是python.org Windows二进制文件。很长一段时间以来,我真的想知道为什么在Windows上进行Python开发如此之薄-直到安装了activestate python。我不隶属于他们。这只是简单的事实。写在每堵墙上:Windows上的Python开发= ActiveState!然后您就可以pypm install mysql-python正常工作了。没有编译狂欢。没有奇怪的错误。没有恐怖。五分钟后就可以开始编码并进行实际工作。这是在Windows上运行的唯一方法。真。

This may read like your grandpa givin advice, but all answers here did not mention the best way: go nd install ActivePython instead of python.org windows binaries. I was really wondering for a long time why Python development on windows was such a pita – until I installed activestate python. I am not affiliated with them. It is just the plain truth. Write it on every wall: Python development on Windows = ActiveState! you then just pypm install mysql-python and everything works smoothly. no compile orgy. no strange errors. no terror. Just start coding and doing real work after five minutes. This is the only way to go on windows. Really.


回答 2

随着Python新手学习Python生态系统,我已经完成了这一步。

  1. 安装setuptools 说明

  2. 安装MySQL 5.1。从此处下载97.6MB MSI 您不能使用Essentials 版本,因为它不包含C库。
    确保选择一个自定义安装,并标记要安装的开发工具/库,因为默认情况下未完成安装。这是获取C头文件所必需的。
    您可以通过在安装目录中查找名为“ include”的文件夹来验证您是否已正确完成此操作。EG C:\ Program Files \ MySQL \ MySQL Server 5.1 \ include。它应该有一堆.h文件。

  3. 此处安装Microsoft Visual Studio C ++ Express 2008 这是获取C编译器所必需的。

  4. 以管理员身份打开命令行(右键单击Cmd快捷方式,然后“以管理员身份运行”。请确保打开一个新窗口 安装这些内容否则您的路径将不会更新,并且安装仍将失败。

  5. 在命令提示符下:

    easy_install -b C:\ temp \ sometempdir mysql-python

    那将失败-可以。

    现在,在您的临时目录C:\ temp \ sometempdir中打开site.cfg,并将“ registry_key”设置编辑为:

    Registry_key =软件\ MySQL AB \ MySQL Server 5.1

    现在将CD放入您的临时目录,并:

    python setup.py干净

    python setup.py安装

    您应该准备好摇滚!

  6. 是一个非常简单的脚本,可以根据需要开始为您学习Python DB API。

As Python newbie learning the Python ecosystem I’ve just completed this.

  1. Install setuptools instructions

  2. Install MySQL 5.1. Download the 97.6MB MSI from here You can’t use the essentials version because it doesnt contain the C libraries.
    Be sure to select a custom install, and mark the development tools / libraries for installation as that is not done by default. This is needed to get the C header files.
    You can verify you have done this correctly by looking in your install directory for a folder named “include”. E.G C:\Program Files\MySQL\MySQL Server 5.1\include. It should have a whole bunch of .h files.

  3. Install Microsoft Visual Studio C++ Express 2008 from here This is needed to get a C compiler.

  4. Open up a command line as administrator (right click on the Cmd shortcut and then “run as administrator”. Be sure to open a fresh window after you have installed those things or your path won’t be updated and the install will still fail.

  5. From the command prompt:

    easy_install -b C:\temp\sometempdir mysql-python

    That will fail – which is OK.

    Now open site.cfg in your temp directory C:\temp\sometempdir and edit the “registry_key” setting to:

    registry_key = SOFTWARE\MySQL AB\MySQL Server 5.1

    now CD into your temp dir and:

    python setup.py clean

    python setup.py install

    You should be ready to rock!

  6. Here is a super simple script to start off learning the Python DB API for you – if you need it.


回答 3

我发现一个人已经成功地为python2.6构建了mysql,并共享了链接,网址为http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe

…您可能会在导入MySQLdb时看到警告,这很正常,不会造成任何伤害,

C:\ Python26 \ lib \ site-packages \ MySQLdb__init __。py:34:DeprecationWarning:sets模块已从set import ImmutableSet中弃用

I found a location were one person had successfully built mysql for python2.6, sharing the link, http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe

…you might see a warning while import MySQLdb which is fine and that won’t hurt anything,

C:\Python26\lib\site-packages\MySQLdb__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import ImmutableSet


回答 4

pymysql呢?它是纯Python,我已经在Windows上成功使用了它,绕过了编译和安装mysql-python的困难。

What about pymysql? It’s pure Python, and I’ve used it on Windows with considerable success, bypassing the difficulties of compiling and installing mysql-python.


回答 5

您不是唯一遇到Python 2.6和MySQL问题的人(http://blog.contriving.net/2009/03/04/using-python-26-mysql-on-windows-is-nearly-impossible/) 。这是说明如何在Python 2.5下运行的方法http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/ 祝您好运

You’re not the only person having problems with Python 2.6 and MySQL (http://blog.contriving.net/2009/03/04/using-python-26-mysql-on-windows-is-nearly-impossible/). Here’s an explanation how it should run under Python 2.5 http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/ Good luck


回答 6


回答 7

http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python上的预编译二进制文件仅对我有用。

  1. 打开 MySQL_python-1.2.5-cp27-none-win_amd64.whl使用zip提取程序文件。
  2. 将内容复制到 C:\Python27\Lib\site-packages\

The precompiled binaries on http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python is just worked for me.

  1. Open MySQL_python-1.2.5-cp27-none-win_amd64.whl file with zip extractor program.
  2. Copy the contents to C:\Python27\Lib\site-packages\

回答 8

在Python 3.4上,我已经从http://www.lfd.uci.edu/~gohlke/pythonlibs/安装了mysqlclient,并使用pip install mysqlclient进行了安装。

On Python 3.4 I’ve installed mysqlclient from http://www.lfd.uci.edu/~gohlke/pythonlibs/ with pip install mysqlclient and it’s working.


回答 9

您可以尝试使用myPySQL。真的很容易使用;Windows无需编译,即使您出于任何原因需要对其进行编译,也只需要安装Python和Visual C(而不是mysql)。

http://code.google.com/p/mypysql/

祝好运

You can try to use myPySQL. It’s really easy to use; no compilation for windows, and even if you need to compile it for any reason, you only need Python and Visual C installed (not mysql).

http://code.google.com/p/mypysql/

Good luck


回答 10

因为我在(pylons / pyramid)virtualenv中运行python,所以无法(有效地)运行以前链接的二进制安装程序。

我在执行Willie的回答步骤时遇到问题,但我确定问题是(可能)我正在运行Windows 7 x64 install,这将mysql的注册表项放在稍有不同的位置,特别是在我的情况下(请注意:正在运行5.5版):“ HKEY_LOCAL_MACHINE \ SOFTWARE \ Wow6432Node \ MySQL AB \ MySQL Server 5.5”。

但是,路径中不能包含“ HKEY_LOCAL_MACHINE \”,否则它将失败。

另外,我必须在步骤3和4之间重新启动。

在完成所有这些工作之后,IMO可以从cygwin运行整个python dev环境会更聪明。

Because I am running python in a (pylons/pyramid) virtualenv, I could not run the binary installers (helpfully) linked to previously.

I had problems following the steps with Willie’s answer, but I determined that the problem is (probably) that I am running windows 7 x64 install, which puts the registry key for mysql in a slightly different location, specifically in my case (note: I am running version 5.5) in: “HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MySQL AB\MySQL Server 5.5”.

HOWEVER, “HKEY_LOCAL_MACHINE\” cannot be included in the path or it will fail.

Also, I had to do a restart between steps 3 and 4.

After working through all of this, IMO it would have been smarter to run the entire python dev environment from cygwin.


回答 11

如果您正在寻找Python 3.2,这似乎是我到目前为止找到的最佳解决方案

资料来源:http : //wiki.python.org/moin/MySQL

If you are looking for Python 3.2 this seems the best solution I found so far

Source: http://wiki.python.org/moin/MySQL


回答 12

您可能还想考虑使用Cygwin,它在存储库中具有mysql python库。

You might want to also consider making use of Cygwin, it has mysql python libraries in the repository.


回答 13

您还可以将pyodbcMySQL Connector / ODBC一起使用,以在Windows上使用MySQL。 Unixodbc也可用于使代码在Linux上兼容。Pyodbc使用标准的Python DB API 2.0,因此如果您坚持要在MySQL / PostgreSQL / SQLite / ODBC / JDBC驱动程序等之间进行切换,应该会比较轻松。

You can also use pyodbc with the MySQL Connector/ODBC to use MySQL on Windows. Unixodbc is also available to make the code compatible on Linux. Pyodbc uses the standard Python DB API 2.0 so if you stick with that switching between MySQL/PostgreSQL/SQLite/ODBC/JDBC drivers etc. should be relatively painless.


回答 14

赞成itsadok的答案,因为它也使我也安装了python 2.7,该软件位于:http : //www.codegood.com/archives/129

upvoted itsadok’s answer because it led me to the installation for python 2.7 as well, which is located here: http://www.codegood.com/archives/129


回答 15

厌倦了MySQLdb的安装问题,而是尝试了pymysql

易于安装;

git clone https://github.com/petehunt/PyMySQL.git
python setup.py install

API几乎相同。

Got sick of the installation troubles with MySQLdb and tried pymysql instead.

Easy setup;

git clone https://github.com/petehunt/PyMySQL.git
python setup.py install

And APIs are pretty much the same.


ImportError:Windows上没有模块命名的站点

问题:ImportError:Windows上没有模块命名的站点

我正在尝试首次安装Python。我从Python网站下载了以下安装程序: Python 2.7.1 Windows Installer(Windows二进制文件-不包括源代码)。然后,我运行安装程序,选择“所有用户”,一切都很好。我将Python安装到默认位置:

C:\Python27

接下来,要测试Python是否已正确安装,我导航到我的Python目录,并在Windows cmd提示符下运行了“ python”命令。它返回以下错误:

ImportError:没有名为站点的模块

当我执行“ python -v”时,我得到以下信息:

#installing zipimport hook
import zipimport # builtin

#ImportError: No module named site #installed zipimport钩子#clear 内置 ._
#clear sys.path #clear sys.argv
#clear sys.ps1 #clear sys.ps2
#clear sys.exitfunc #clear sys.exc_type
#clear sys.exc_value #clear sys.exc_traceback
#clear sys.last_type #clear sys.last_value
#clear sys.last_traceback #clear sys.path_hooks
#clear sys.path_importer_cache #clear sys.meta_path
#clear sys.flags #clear sys.float_info
#restore sys.stdin #恢复sys.stdout
#restore sys.stderr #cleanup
#cleanup [1 ] zipimport #cleanup [1]信号
#cleanup[1 ] exceptions #cleanup [1] _warnings
#cleanup sys 内置的
#cleanup ints: 6 unfreed ints cleanup #cleanup浮动

当我执行dir时,C:\Python27\Lib\site.py*我得到以下信息:

C:\ Users \ Mimminito> dir C:\ Python27 \ Lib \ site.py *
驱动器C中的卷没有标签。
卷序列号是DAB9-A863

C:\ Python27 \ Lib目录

13/11/2010 20:08 20,389 site.py
1文件20,389字节
0目录694,910,976字节免费

有任何想法吗?

I am trying to install Python for the first time. I downloaded the following installer from the Python website: Python 2.7.1 Windows Installer (Windows binary — does not include source). I then ran the installer, selected ‘All Users’ and all was fine. I installed Python into the default location:

C:\Python27

Next, to test that Python was installed correctly, I navigated to my Python Directory, and ran the “python” command in the windows cmd prompt. It returns me the following error:

ImportError: No module named site

When I do ‘python -v’ I get the following:

#installing zipimport hook
import zipimport # builtin
#installed zipimport hook
#ImportError: No module named site #clear builtin._
#clear sys.path #clear sys.argv
#clear sys.ps1 #clear sys.ps2
#clear sys.exitfunc #clear sys.exc_type
#clear sys.exc_value #clear sys.exc_traceback
#clear sys.last_type #clear sys.last_value
#clear sys.last_traceback #clear sys.path_hooks
#clear sys.path_importer_cache #clear sys.meta_path
#clear sys.flags #clear sys.float_info
#restore sys.stdin #restore sys.stdout
#restore sys.stderr #cleanup main
#cleanup[1] zipimport #cleanup[1] signal
#cleanup[1] exceptions #cleanup[1] _warnings
#cleanup sys #cleanup builtin
#cleanup ints: 6 unfreed ints #cleanup floats

When I do dir C:\Python27\Lib\site.py* I get the following:

C:\Users\Mimminito>dir C:\Python27\Lib\site.py*
Volume in drive C has no label.
Volume Serial Number is DAB9-A863

Directory of C:\Python27\Lib

13/11/2010 20:08 20,389 site.py
1 File(s) 20,389 bytes
0 Dir(s) 694,910,976 bytes free

Any ideas?


回答 0

我已经为自己研究了近一天的问题,终于取得了突破。试试这个:

  1. 设置PYTHONPATH / PYTHONHOME变量

    右键单击开始菜单中的“ 计算机”图标,然后转到属性。在左侧标签上,转到高级系统设置。在出现的窗口中,转到“ 高级”选项卡,然后在底部单击“ 环境变量”。单击用户变量列表,然后开始键入Python,然后重复“ 系统变量”,以确保您没有为PYTHONPATH或PYTHONHOME设置错误的变量。接下来,添加新变量(我也可以在System中而不是User中使用,尽管它也可能对User也适用):PYTHONPATH,设置为C:\ Python27 \ Lib。,设置为C:\ Python27PYTHONHOME

希望这可以帮助!

I’ve been looking into this problem for myself for almost a day and finally had a breakthrough. Try this:

  1. Setting the PYTHONPATH / PYTHONHOME variables

    Right click the Computer icon in the start menu, go to properties. On the left tab, go to Advanced system settings. In the window that comes up, go to the Advanced tab, then at the bottom click Environment Variables. Click in the list of user variables and start typing Python, and repeat for System variables, just to make certain that you don’t have mis-set variables for PYTHONPATH or PYTHONHOME. Next, add new variables (I did in System rather than User, although it may work for User too): PYTHONPATH, set to C:\Python27\Lib. PYTHONHOME, set to C:\Python27.

Hope this helps!


回答 1

快速解决方案:设置PYTHONHOME和PYTHONPATH并在PATH上包含PYTHONHOME

例如,如果您安装到c:\ Python27

set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%

确保您在PYTHON *变量上没有结尾的’\’,这似乎会使它破坏。

Quick solution: set PYTHONHOME and PYTHONPATH and include PYTHONHOME on PATH

For example if you installed to c:\Python27

set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%

Make sure you don’t have a trailing ‘\’ on the PYTHON* vars, this seems to break it aswel.


回答 2

在安装Windows Python和Cygwin Python并尝试从Cygwin运行Cygwin Python之后,出现了这个问题。我export通过PYTHONHOME = / usr /和PYTHONPATH = / usr / lib / python2.7 解决了它

I was having this issue after installing both Windows Python and Cygwin Python, and trying to run Cygwin Python from Cygwin. I solved it by exporting PYTHONHOME=/usr/ and PYTHONPATH=/usr/lib/python2.7


回答 3

确保正确设置了PYTHONHOME环境变量。如果PYTHONHOME指向无效的位置或您要运行的其他Python安装,您将收到此错误。

试试这个:

C:\>set PYTHONHOME=C:\Python27
C:\>python

setx PYTHONHOME C:\Python27

将其永久设置为后续命令提示符

Make sure your PYTHONHOME environment variable is set correctly. You will receive this error if PYTHONHOME is pointing to invalid location or to another Python installation you are trying to run.

Try this:

C:\>set PYTHONHOME=C:\Python27
C:\>python

Use

setx PYTHONHOME C:\Python27

to set this permanently for subsequent command prompts


回答 4

找到site.py并将其路径添加到PYTHONPATH中。这样可以解决您的问题。

Locate site.py and add its path in PYTHONPATH. This will solve your problem.


回答 5

您是否要从Cygwin运行Windows Python?我有同样的问题。Cygwin中的Python无法导入站点。Cmd中的Python可以工作。

看起来您需要确保通过以下方式运行PYTHONHOME和PYTHONPATH cygwin -aw来使它们成为Windows路径。另外,python似乎使用了一些不正确的路径。

我想我需要通过cygwin安装python才能正常工作。

Are you trying to run Windows Python from Cygwin? I’m having the same problem. Python in Cygwin fails to import site. Python in Cmd works.

It looks like you need to make sure you run PYTHONHOME and PYTHONPATH through cygwin -aw to make them Windows paths. Also, python seems to be using some incorrect paths.

I think I’ll need to install python through cygwin to get it working.


回答 6

对于Windows 10(按照@slckin回答),可以通过以下命令在命令行中进行设置:

setx PYTHONHOME "C:\Python27"
setx PYTHONPATH "C:\Python27\Lib"
setx PATH "%PYTHONHOME%;%PATH%"

For Windows 10 (follow up on @slckin answer), this can be set through the command line with:

setx PYTHONHOME "C:\Python27"
setx PYTHONPATH "C:\Python27\Lib"
setx PATH "%PYTHONHOME%;%PATH%"

回答 7

就我而言,问题是另一个site.py文件,由于PATH设置,它比Python \ Lib中的文件更早被解决。

环境:Windows 10 Pro,Python27。

我的桌面安装了pgAdmin,它具有文件C:\ Program Files(x86)\ pgAdmin \ venv \ Lib \ site.py。由于PATH环境变量比Python更早拥有pdAdmin的目录(显然这是一个坏主意),因此首先找到pgAdmin的site.py。

解决该问题所需要做的就是在PATH中将pgAdmin的主页移到比Python晚的地方

In my case, the issue was another site.py file, that was resolved earlier than the one from Python\Lib, due to PATH setting.

Environment: Windows 10 Pro, Python27.

My desktop has pgAdmin installed, which has file C:\Program Files (x86)\pgAdmin\venv\Lib\site.py. Because PATH environment variable had pdAdmin’s home earlier than Python (apparently a bad idea in the first place), pgAdmin’s site.py was found first.

All I had to do to fix the issue was to move pgAdmin’s home later than Python, in PATH


回答 8

对我而言,发生这种情况是因为我安装了2个版本的python-python 27和python 3.3。这两个文件夹都设置了路径变量,因此存在此问题。为了解决这个问题,我将python27移到了temp文件夹,因为我对python 3.3没问题。因此,请检查诸如PATH,PYTHONHOME之类的环境变量,因为这可能是一个问题。谢谢。

For me it happened because I had 2 versions of python installed – python 27 and python 3.3. Both these folder had path variable set, and hence there was this issue. To fix, this, I moved python27 to temp folder, as I was ok with python 3.3. So do check environment variables like PATH,PYTHONHOME as it may be a issue. Thanks.


回答 9

如果有人发现非管理员用户仍无法使用它:

错误示例:

ImportError: No module named iso8601

您需要为easy_install设置“ –always-unzip”选项:

easy_install --always-unzip python-keystoneclient

它将解压缩您的egg文件,并允许导入找到em。

If somebody will find that it’s still not working under non-admin users:

Example error:

ImportError: No module named iso8601

you need to set ‘–always-unzip’ option for easy_install:

easy_install --always-unzip python-keystoneclient

It will unzip your egg files and will allow import to find em.


回答 10

ImportError: No module named site在安装python 2.7.11时遇到了同样的问题

最初我有Python2.5,PYTHONHOME路径设置为Python2.5。我将其重命名为,C:\Python27\并解决了该问题。

I went through the same issue of ImportError: No module named site while installing python 2.7.11

Initially I had Python2.5 and the PYTHONHOME path was set to Python2.5. I renamed it to C:\Python27\ and it resolved the problem.


回答 11

您可以尝试“ 开源Active Python设置”,它是Windows的出色Python安装程序。您只需要卸载并安装版本即可。

You may try the Open Source Active Python Setup which is a well done Python installer for Windows. You just have to desinstall your version and install it…


回答 12

我对slckin的答案投了赞成票。我的问题是我考虑周全,并在路径周围加了双引号。我删除了所有三个变量的双引号:PYTHONHOME,PYTHONPATH和PATH。请注意,该文件位于cmd或bat文件中,用于设置其他工具的环境。但是,双引号可能在图标设置中很有用。打字

揭示了报价在路径中的位置而不是按预期下降。我还缩短了PATH,使其长度少于256个字符。

I up voted slckin’s answer. My problem was that I was thoughtful and added double quotes around the paths. I removed the double quotes in all of the three variables: PYTHONHOME, PYTHONPATH, and PATH. Note that this was in a cmd or bat file to setup the environment for other tools. However, the double quotes may be useful in an icon setting. Typing

set

revealed that the quotes where in the path and not dropped as expected. I also shorted the PATH so that it was less than 256 characters long.


回答 13

我有一个非常依赖Python的应用程序,并随着新版本的发布保持python 2.7.x的最新性。直到2.7.11,当我遇到相同的No module named site错误时,一切都很好。我已将PYTHONHOME设置为c:\Python27且正在运行。但是仍然有一个谜,为什么在以前的版本中不需要它,现在需要这样做。而且,如果需要,安装程序为什么不设置此变量?

I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same “No module named site” error. I’ve set PYTHONHOME to c:\Python27 and it’s working. But the mystery remains why this is now needed when it wasn’t with previous releases. And, if it is needed, why doesn’t the installer set this var?


回答 14

我有同样的问题。我的解决方案是修复Python安装。(这是一个新安装,因此我没想到会出现问题,但现在已解决。)

要修复(Windows 7):

  1. 转到控制面板->程序->程序和功能
  2. 单击已安装的Python版本,然后按“卸载/更改”。
  3. 请按照说明修复安装。

I had the same problem. My solution was to repair the Python installation. (It was a new installation so I did not expect a problem but now it is solved.)

To repair (Windows 7):

  1. go to Control Panel -> Programs -> Programs and Features
  2. click on the Python version installed and then press Uninstall/Change.
  3. follow the instructions to repair the installation.

回答 15

从PyYAML主页安装yaml:http ://www.pyyaml.org/wiki/PyYAML

选择适合您的OS和Python的版本。

Install yaml from the PyYAML home pagee: http://www.pyyaml.org/wiki/PyYAML

Select the appropriate version for your OS and Python.


如何在Windows上运行多个Python版本

问题:如何在Windows上运行多个Python版本

我在计算机上安装了两个版本的Python(版本2.6和2.5)。我想为一个项目运行2.6,为另一个项目运行2.5。

如何指定我要使用哪个?

我正在使用Windows XP SP2。

I had two versions of Python installed on my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another.

How can I specify which I want to use?

I am working on Windows XP SP2.


回答 0

运行不同的Python副本就像启动正确的可执行文件一样容易。您提到您已经从命令行通过简单输入以下内容启动了python实例:python

这在Windows下的作用是拖曳%PATH%环境变量,检查可执行文件,无论是批处理文件(.bat),命令文件(.cmd)还是其他要运行的可执行文件(由可执行文件控制PATHEXT环境变量)是否与给定名称匹配。当找到正确的文件来运行时,该文件正在运行。

现在,如果您已经安装了两个Python版本2.5和2.6,则路径中将同时包含它们的两个目录,例如 PATH=c:\python\2.5;c:\python\2.6但是Windows将在找到匹配项时停止检查该路径。

您真正需要做的是显式调用一个或两个应用程序,例如c:\python\2.5\python.exec:\python\2.6\python.exe

另一种选择是创建一个快捷方式,以分别python.exe调用其中一个python25和另一个python26;然后python25,您只需在命令行上运行即可。

Running a different copy of Python is as easy as starting the correct executable. You mention that you’ve started a python instance, from the command line, by simply typing python.

What this does under Windows, is to trawl the %PATH% environment variable, checking for an executable, either batch file (.bat), command file (.cmd) or some other executable to run (this is controlled by the PATHEXT environment variable), that matches the name given. When it finds the correct file to run the file is being run.

Now, if you’ve installed two python versions 2.5 and 2.6, the path will have both of their directories in it, something like PATH=c:\python\2.5;c:\python\2.6 but Windows will stop examining the path when it finds a match.

What you really need to do is to explicitly call one or both of the applications, such as c:\python\2.5\python.exe or c:\python\2.6\python.exe.

The other alternative is to create a shortcut to the respective python.exe calling one of them python25 and the other python26; you can then simply run python25 on your command line.


回答 1

为该问题添加了两个解决方案:

  • 使用pylauncher(如果您使用的是Python 3.3或更高版本,则无需安装它,因为它已经随Python一起提供了),然后在脚本中添加shebang行;

#! c:\[path to Python 2.5]\python.exe-适用于要与Python 2.5一起运行
#! c:\[path to Python 2.6]\python.exe的脚本-适用于要与Python 2.6一起运行的脚本

或者代替运行python命令run pylauncher command(py)指定要使用哪个版本的Python;或者

py -2.6–版本2.6
py -2–最新安装的版本2.x
py -3.4–版本3.4
py -3–最新安装的版本3.x

virtualenv -p c:\[path to Python 2.5]\python.exe [path where you want to have virtualenv using Python 2.5 created]\[name of virtualenv]

virtualenv -p c:\[path to Python 2.6]\python.exe [path where you want to have virtualenv using Python 2.6 created]\[name of virtualenv]

例如

virtualenv -p c:\python2.5\python.exe c:\venvs\2.5

virtualenv -p c:\python2.6\python.exe c:\venvs\2.6

那么您可以激活第一个并像这样使用Python 2.5,
c:\venvs\2.5\activate
并且当您想切换到Python 2.6时,

deactivate  
c:\venvs\2.6\activate

Adding two more solutions to the problem:

  • Use pylauncher (if you have Python 3.3 or newer there’s no need to install it as it comes with Python already) and either add shebang lines to your scripts;

#! c:\[path to Python 2.5]\python.exe – for scripts you want to be run with Python 2.5
#! c:\[path to Python 2.6]\python.exe – for scripts you want to be run with Python 2.6

or instead of running python command run pylauncher command (py) specyfing which version of Python you want;

py -2.6 – version 2.6
py -2 – latest installed version 2.x
py -3.4 – version 3.4
py -3 – latest installed version 3.x

virtualenv -p c:\[path to Python 2.5]\python.exe [path where you want to have virtualenv using Python 2.5 created]\[name of virtualenv]

virtualenv -p c:\[path to Python 2.6]\python.exe [path where you want to have virtualenv using Python 2.6 created]\[name of virtualenv]

for example

virtualenv -p c:\python2.5\python.exe c:\venvs\2.5

virtualenv -p c:\python2.6\python.exe c:\venvs\2.6

then you can activate the first and work with Python 2.5 like this
c:\venvs\2.5\activate
and when you want to switch to Python 2.6 you do

deactivate  
c:\venvs\2.6\activate

回答 2

从Python 3.3开始,有适用于Windows的官方Python启动器http://www.python.org/dev/peps/pep-0397/)。现在,您也可以#!pythonX在Windows上使用来确定所需的解释器版本。在我的其他评论中查看更多详细信息或阅读PEP 397。

总结:py script.pyPython的版本中规定发布#!,如果或Python 2 #!缺失。该py -3 script.py运行Python 3。

From Python 3.3 on, there is the official Python launcher for Windows (http://www.python.org/dev/peps/pep-0397/). Now, you can use the #!pythonX to determine the wanted version of the interpreter also on Windows. See more details in my another comment or read the PEP 397.

Summary: The py script.py launches the Python version stated in #! or Python 2 if #! is missing. The py -3 script.py launches the Python 3.


回答 3

按照@alexander,您可以建立如下的符号链接集。将它们放在您的路径中包含的某个位置,以便可以轻松调用它们

> cd c:\bin
> mklink python25.exe c:\python25\python.exe
> mklink python26.exe c:\python26\python.exe

只要您将c:\ bin或您放置在其中的任何位置都在路径中,现在就可以

> python25

As per @alexander you can make a set of symbolic links like below. Put them somewhere which is included in your path so they can be easily invoked

> cd c:\bin
> mklink python25.exe c:\python25\python.exe
> mklink python26.exe c:\python26\python.exe

As long as c:\bin or where ever you placed them in is in your path you can now go

> python25

回答 4

  1. 安装python

    • C:\ Python27
    • C:\ Python36
  2. 环境变量

    • PYTHON2_HOME: C:\Python27
    • PYTHON3_HOME: C:\Python36
    • Path: %PYTHON2_HOME%;%PYTHON2_HOME%\Scripts;%PYTHON3_HOME%;%PYTHON3_HOME%\Scripts;
  3. 文件重命名

    • C:\ Python27 \ python.exe→C:\ Python27 \ python2.exe
    • C:\ Python36 \ python.exe→C:\ Python36 \ python3.exe
  4. 点子

    • python2 -m pip install package
    • python3 -m pip install package
  1. install python

    • C:\Python27
    • C:\Python36
  2. environment variable

    • PYTHON2_HOME: C:\Python27
    • PYTHON3_HOME: C:\Python36
    • Path: %PYTHON2_HOME%;%PYTHON2_HOME%\Scripts;%PYTHON3_HOME%;%PYTHON3_HOME%\Scripts;
  3. file rename

    • C:\Python27\python.exe → C:\Python27\python2.exe
    • C:\Python36\python.exe → C:\Python36\python3.exe
  4. pip

    • python2 -m pip install package
    • python3 -m pip install package

回答 5

例如对于3.6版本类型py -3.6。如果您同时具有32位和64位版本,则只需键入py -3.6-64或即可py -3.6-32

For example for 3.6 version type py -3.6. If you have also 32bit and 64bit versions, you can just type py -3.6-64 or py -3.6-32.


回答 6

当您安装Python时,它不会覆盖其他主要版本的其他安装。因此,安装Python 2.5.x不会覆盖Python 2.6.x,尽管安装2.6.6会覆盖2.6.5。

因此,您只需安装它即可。然后,调用所需的Python版本。例如:

C:\Python2.5\Python.exe

适用于Windows上的Python 2.5和

C:\Python2.6\Python.exe

适用于Windows上的Python 2.6,或

/usr/local/bin/python-2.5

要么

/usr/local/bin/python-2.6

Windows Unix(包括Linux和OS X)上。

在Unix(包括Linux和OS X)上python安装时,将安装通用命令,这是最后安装的命令。大多数情况下这不是问题,因为大多数脚本会显式调用/usr/local/bin/python2.5或一些用于防止这种情况的文件。但是,如果您不想这样做,并且您可能不想这样做,可以这样安装:

./configure
make
sudo make altinstall

请注意,“ altinstall”表示它将安装它,但不会代替python命令。

python据我所知,在Windows上您没有得到全局命令,所以这不是问题。

When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5.

So you can just install it. Then you call the Python version you want. For example:

C:\Python2.5\Python.exe

for Python 2.5 on windows and

C:\Python2.6\Python.exe

for Python 2.6 on windows, or

/usr/local/bin/python-2.5

or

/usr/local/bin/python-2.6

on Windows Unix (including Linux and OS X).

When you install on Unix (including Linux and OS X) you will get a generic python command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don’t want to do that, and you probably don’t you can install it like this:

./configure
make
sudo make altinstall

Note the “altinstall” that means it will install it, but it will not replace the python command.

On Windows you don’t get a global python command as far as I know so that’s not an issue.


回答 7

我强烈推荐pyenv-win项目。

由于kirankotari的工作,现在我们有了Windows版本的pyenv。

I strongly recommend the pyenv-win project.

Thanks to kirankotari‘s work, now we have a Windows version of pyenv.


回答 8

这是一个快速的技巧:

  1. 转到您要运行的python版本的目录
  2. 右键点击python.exe
  3. 选择“ 创建快捷方式
  4. 给该快捷方式起个呼叫的名字(我使用p27,p33等)
  5. 将该快捷方式移至您的主目录(C:\Users\Your name
  6. 打开命令提示符并输入name_of_your_shortcut.lnk(我使用p27.lnk

Here’s a quick hack:

  1. Go to the directory of the version of python you want to run
  2. Right click on python.exe
  3. Select ‘Create Shortcut
  4. Give that shortcut a name to call by( I use p27, p33 etc.)
  5. Move that shortcut to your home directory(C:\Users\Your name)
  6. Open a command prompt and enter name_of_your_shortcut.lnk(I use p27.lnk)

回答 9

cp c:\ python27 \ bin \ python.exe作为python2.7.exe

cp c:\ python34 \ bin \ python.exe作为python3.4.exe

它们都在系统路径中,请选择要运行的版本

C:\Users\username>python2.7
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

C:\Users\username>python3.4
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

cp c:\python27\bin\python.exe as python2.7.exe

cp c:\python34\bin\python.exe as python3.4.exe

they are all in the system path, choose the version you want to run

C:\Users\username>python2.7
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

C:\Users\username>python3.4
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

回答 10

使用批处理文件进行切换,在Windows 7上轻松高效。我使用以下命令:

在环境变量对话框(C:\ Windows \ System32 \ SystemPropertiesAdvanced.exe)中,

在用户变量部分

  1. 在路径环境变量中添加了%pathpython%

  2. 删除了对python路径的任何引用

在系统变量部分

  1. 删除了对python路径的任何引用

我为每个python安装创建了批处理文件(例如3.4 x64

名称= SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-)只是为了记住。

文件内容=

     Set PathPython=C:\Python36AMD64\Scripts\;C:\Python36AMD64\;C:\Tcl\bin

     setx PathPython %PathPython%

要在版本之间切换,我在admin模式下执行批处理文件。

!!!!! 该更改对SUBSEQUENT命令提示符窗口OPENED有效。!!!

因此,我对此有完全的控制权。

Using a batch file to switch, easy and efficient on windows 7. I use this:

In the environment variable dialog (C:\Windows\System32\SystemPropertiesAdvanced.exe),

In the section user variables

  1. added %pathpython% to the path environment variable

  2. removed any references to python pathes

In the section system variables

  1. removed any references to python pathes

I created batch files for every python installation (exmple for 3.4 x64

Name = SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-) just to remember.

Content of the file =

     Set PathPython=C:\Python36AMD64\Scripts\;C:\Python36AMD64\;C:\Tcl\bin

     setx PathPython %PathPython%

To switch between versions, I execute the batch file in admin mode.

!!!!! The changes are effective for the SUBSEQUENT command prompt windows OPENED. !!!

So I have exact control on it.


回答 11

在Windows上运行多个版本的python的最简单方法如下所述:

1)从python.org/downloads下载最新版本的python通过选择系统的相关版本,。

2)运行安装程序,然后选择将python 3.x添加到路径中以在python 3中自动设置路径(您只需单击复选框)。对于python 2,请打开python 2安装程序,选择所需的任何首选项,但只需记住将Add python.exe设置为路径将其安装在本地硬盘上,现在只需单击下一步,然后等待安装程序完成即可。

3)两个安装都完成后。右键单击我的计算机-转到属性-选择高级系统设置-转到环境变量-单击系统变量下的新建,然后添加一个新的系统变量,其变量名称PY_PYTHON并将此变量值设置为3。现在单击确定,您应该完成。

4)现在要对此进行测试,请打开命令提示符。一旦进入pythonpy,它应该打开python3

5)现在通过键入exit()退出 python3 。现在输入py -2应该会打开python 2。

如果这些都不起作用,请重新启动计算机,如果问题仍然存在,请卸载所有组件并重复步骤。

谢谢。

The easiest way to run multiple versions of python on windows is described below as follows:-

1)Download the latest versions of python from python.org/downloads by selecting the relevant version for your system.

2)Run the installer and select Add python 3.x to the path to set path automatically in python 3 (you just have to click the checkbox). For python 2 open up your python 2 installer, select whatever preferences you want but just remember to set Add python.exe to path to Will be installed on local hard drive, Now just click next and wait for the installer to finish.

3)When both the installations are complete. Right click on my computer–Go to properties–Select advanced system settings–Go to environment variables–Click on new under System variables and add a new system variable with variable name as PY_PYTHON and set this variable value to 3. Now click on OK and you should be done.

4)Now to test this open the command prompt. Once you are in there type python or py, It should open up python3.

5)Now exit out of python3 by typing exit(). Now type py -2 it should open python 2.

If none of this works then restart the computer and if the problem still persists then uninstall everything and repeat the steps.

Thanks.


回答 12

您可以从Anaconda Navigator图形化地创建不同的python开发环境。在使用不同的python版本时遇到相同的问题,因此我使用anaconda导航器创建了不同的python开发环境,并在每个环境中使用了不同的python版本。

这是帮助文档。

https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/

You can create different python development environments graphically from Anaconda Navigator. I had same problem while working with different python versions so I used anaconda navigator to create different python development environments and used different python versions in each environments.

Here is the help documentation for this.

https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/


回答 13

使用Rapid Environment Editor, 您可以将所需的Python安装目录推到顶部。例如,要从c:\ Python27目录启动python,请确保c:\ Python27目录在Path环境变量中的c:\ Python36目录之前或之上。根据我的经验,正在执行Path环境中找到的第一个python可执行文件。例如,我已经在Python27上安装了MSYS2,并且由于我已经将C:\ MSYS2添加到C:\ Python36之前的路径中,因此正在执行C:\ MSYS2 ….文件夹中的python.exe。

Using the Rapid Environment Editor you can push to the top the directory of the desired Python installation. For example, to start python from the c:\Python27 directory, ensure that c:\Python27 directory is before or on top of the c:\Python36 directory in the Path environment variable. From my experience, the first python executable found in the Path environment is being executed. For example, I have MSYS2 installed with Python27 and since I’ve added C:\MSYS2 to the path before C:\Python36, the python.exe from the C:\MSYS2…. folder is being executed.


回答 14

只需调用正确的可执行文件

Just call the correct executable


Windows Scipy安装:未找到Lapack / Blas资源

问题:Windows Scipy安装:未找到Lapack / Blas资源

我正在尝试在64位Windows 7桌面上安装python和一系列软件包。我已经安装了Python 3.4,已经安装了Microsoft Visual Studio C ++,并且已经成功安装了numpy,pandas和其他一些软件。尝试安装scipy时出现以下错误;

numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

我正在离线使用pip install,我正在使用的安装命令是;

pip install --no-index --find-links="S:\python\scipy 0.15.0" scipy

我已经阅读了有关要求编译器的信息,如果我正确理解的话,则是VS C ++编译器。我正在使用2010版本,就像在使用Python 3.4。这对于其他软件包也有效。

我必须使用窗口二进制文件还是有办法让pip安装正常工作?

非常感谢您的帮助

I am trying to install python and a series of packages onto a 64bit windows 7 desktop. I have installed Python 3.4, have Microsoft Visual Studio C++ installed, and have successfully installed numpy, pandas and a few others. I am getting the following error when trying to install scipy;

numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

I am using pip install offline, the install command I am using is;

pip install --no-index --find-links="S:\python\scipy 0.15.0" scipy

I have read the posts on here about requiring a compiler which if I understand correctly is the VS C++ compiler. I am using the 2010 version as I am using Python 3.4. This has worked for other packages.

Do I have to use the window binary or is there a way I can get pip install to work?

Many thanks for the help


回答 0

此处介绍了在Windows 7 64位系统上不安装SciPy的BLAS / LAPACK库的解决方案:

http://www.scipy.org/scipylib/building/windows.html

安装Anaconda会容易得多,但是如果不付费就无法获得Intel MKL或GPU的支持(它们在MKL Optimizations和Anaconda的加速附件中-我不确定他们是否同时使用PLASMA和MAGMA) 。通过MKL优化,numpy在大型矩阵计算上的性能优于IDL十倍。MATLAB内部使用Intel MKL库并支持GPU计算,因此如果他们是学生,则不妨将其作为价格使用(MATLAB为50美元,并行计算工具箱为10美元)。如果您获得了Intel Parallel Studio的免费试用版,它将附带MKL库以及C ++和FORTRAN编译器,如果您想在Windows上从MKL或ATLAS安装BLAS和LAPACK,它们将派上用场:

http://icl.cs.utk.edu/lapack-for-windows/lapack/

Parallel Studio还带有Intel MPI库,可用于群集计算应用程序及其最新的Xeon处理器。尽管使用MKL优化来构建BLAS和LAPACK的过程并非易事,但针对Python和R这样做的好处却是巨大的,如以下英特尔网络研讨会所述:

https://software.intel.com/zh-CN/articles/powered-by-mkl-accelerating-numpy-and-scipy-performance-with-intel-mkl-python

Anaconda和Enthought通过使此功能和其他一些事情更易于部署而建立了业务。但是,愿意做一点工作(一点学习)的人可以免费使用它。

对于那些谁使用R,你现在可以得到优化MKL BLAS和LAPACK免费使用R打开从革命Analytics(分析)。

编辑:Anaconda Python现在附带MKL优化,以及通过Intel Python发行版对许多其他Intel库优化的支持。但是,Accelerate库(以前称为NumbaPro)中对Anaconda的GPU支持仍然超过1万美元!最好的替代方法可能是PyCUDA和scikit-cuda,因为铜头鱼(基本上是Anaconda Accelerate的免费版本)不幸在五年前停止开发。如果有人想在他们离开的地方接机,可以在这里找到。

The solution to the absence of BLAS/LAPACK libraries for SciPy installations on Windows 7 64-bit is described here:

http://www.scipy.org/scipylib/building/windows.html

Installing Anaconda is much easier, but you still don’t get Intel MKL or GPU support without paying for it (they are in the MKL Optimizations and Accelerate add-ons for Anaconda – I’m not sure if they use PLASMA and MAGMA either). With MKL optimization, numpy has outperformed IDL on large matrix computations by 10-fold. MATLAB uses the Intel MKL library internally and supports GPU computing, so one might as well use that for the price if they’re a student ($50 for MATLAB + $10 for the Parallel Computing Toolbox). If you get the free trial of Intel Parallel Studio, it comes with the MKL library, as well as C++ and FORTRAN compilers that will come in handy if you want to install BLAS and LAPACK from MKL or ATLAS on Windows:

http://icl.cs.utk.edu/lapack-for-windows/lapack/

Parallel Studio also comes with the Intel MPI library, useful for cluster computing applications and their latest Xeon processsors. While the process of building BLAS and LAPACK with MKL optimization is not trivial, the benefits of doing so for Python and R are quite large, as described in this Intel webinar:

https://software.intel.com/en-us/articles/powered-by-mkl-accelerating-numpy-and-scipy-performance-with-intel-mkl-python

Anaconda and Enthought have built businesses out of making this functionality and a few other things easier to deploy. However, it is freely available to those willing to do a little work (and a little learning).

For those who use R, you can now get MKL optimized BLAS and LAPACK for free with R Open from Revolution Analytics.

EDIT: Anaconda Python now ships with MKL optimization, as well as support for a number of other Intel library optimizations through the Intel Python distribution. However, GPU support for Anaconda in the Accelerate library (formerly known as NumbaPro) is still over $10k USD! The best alternatives for that are probably PyCUDA and scikit-cuda, as copperhead (essentially a free version of Anaconda Accelerate) unfortunately ceased development five years ago. It can be found here if anybody wants to pick up where they left off.


回答 1

以下链接应解决Windows和SciPy的所有问题;只需选择适当的下载即可。我能够毫无问题地安装该软件包。我尝试过的所有其他解决方案都让我头疼。

来源:http : //www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

命令:

 pip install [Local File Location]\[Your specific file such as scipy-0.16.0-cp27-none-win_amd64.whl]

假定您已经安装了以下软件:

  1. 使用Python工具安装Visual Studio 2015/2013
    (在2015年安装时已集成到安装选项中)

  2. 安装用于Python的Visual Studio C ++编译器
    来源:http : //www.microsoft.com/zh-cn/download/details.aspx?id=44266
    文件名:VCForPython27.msi

  3. 选择安装的Python版本
    来源:python.org
    文件名(例如):python-2.7.10.amd64.msi

The following link should solve all problems with Windows and SciPy; just choose the appropriate download. I was able to pip install the package with no problems. Every other solution I have tried gave me big headaches.

Source: http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

Command:

 pip install [Local File Location]\[Your specific file such as scipy-0.16.0-cp27-none-win_amd64.whl]

This assumes you have installed the following already:

  1. Install Visual Studio 2015/2013 with Python Tools
    (Is integrated into the setup options on install of 2015)

  2. Install Visual Studio C++ Compiler for Python
    Source: http://www.microsoft.com/en-us/download/details.aspx?id=44266
    File Name: VCForPython27.msi

  3. Install Python Version of choice
    Source: python.org
    File Name (e.g.): python-2.7.10.amd64.msi


回答 2

我的python版本是2.7.10,64位Windows 7。

  1. scipy-0.18.0-cp27-cp27m-win_amd64.whl从下载http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
  2. 打开 cmd
  3. 确保scipy-0.18.0-cp27-cp27m-win_amd64.whl位于cmd当前目录中,然后键入pip install scipy-0.18.0-cp27-cp27m-win_amd64.whl

将成功安装。

My python’s version is 2.7.10, 64-bits Windows 7.

  1. Download scipy-0.18.0-cp27-cp27m-win_amd64.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
  2. Open cmd
  3. Make sure scipy-0.18.0-cp27-cp27m-win_amd64.whl is in cmd‘s current directory, then type pip install scipy-0.18.0-cp27-cp27m-win_amd64.whl.

It will be successful installed.


回答 3

抱歉necro,但这是第一个Google搜索结果。这是为我工作的解决方案:

  1. http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy下载numpy + mkl滚轮 。使用与python版本相同的版本(使用python -V检查)。例如。如果您的python是3.5.2,请下载显示cp35的转盘

  2. 打开命令提示符,然后导航到下载滚轮的文件夹。运行命令:pip install [wheel文件名]

  3. 从以下网址下载SciPy滚轮:http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy (类似于上述步骤)。

  4. 如上所述,pip install [wheel的文件名]

Sorry to necro, but this is the first google search result. This is the solution that worked for me:

  1. Download numpy+mkl wheel from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy. Use the version that is the same as your python version (check using python -V). Eg. if your python is 3.5.2, download the wheel which shows cp35

  2. Open command prompt and navigate to the folder where you downloaded the wheel. Run the command: pip install [file name of wheel]

  3. Download the SciPy wheel from: http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy (similar to the step above).

  4. As above, pip install [file name of wheel]


回答 4

这是我一切正常的顺序。第二点是最重要的。科学需要Numpy+MKL,而不仅仅是香草Numpy

  1. 安装python 3.5
  2. pip install "file path"(从此处http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy下载Numpy + MKL轮子)
  3. pip install scipy

This was the order I got everything working. The second point is the most important one. Scipy needs Numpy+MKL, not just vanilla Numpy.

  1. Install python 3.5
  2. pip install "file path" (download Numpy+MKL wheel from here http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy)
  3. pip install scipy

回答 5

如果您使用的是Windows和Visual Studio 2015

输入以下命令

  • “康达安装numpy的”
  • “康达安装熊猫”
  • “ conda安装scipy”

If you are working with Windows and Visual Studio 2015

Enter the following commands

  • “conda install numpy”
  • “conda install pandas”
  • “conda install scipy”

回答 6

我的5美分;您可以从https://github.com/scipy/scipy/releases安装整个(预编译的)SciPy

祝好运!

My 5 cents; You can just install the entire (pre-compiled) SciPy from https://github.com/scipy/scipy/releases

Good Luck!


回答 7

在Windows中简单快速地安装Scipy

  1. http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy下载适用于您的Python版本的正确Scipy软件包(例如,适用于python 3.5和Windows x64的正确软件包scipy-0.19.1-cp35-cp35m-win_amd64.whl)。
  2. cmd在包含下载的Scipy软件包的目录中打开。
  3. 键入pip install <<your-scipy-package-name>>(例如pip install scipy-0.19.1-cp35-cp35m-win_amd64.whl)。

Simple and Fast Installation of Scipy in Windows

  1. From http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy download the correct Scipy package for your Python version (e.g. the correct package for python 3.5 and Windows x64 is scipy-0.19.1-cp35-cp35m-win_amd64.whl).
  2. Open cmd inside the directory containing the downloaded Scipy package.
  3. Type pip install <<your-scipy-package-name>> (e.g. pip install scipy-0.19.1-cp35-cp35m-win_amd64.whl).

回答 8

对于 python27 1,安装numpy + mkl(下载链接:http : //www.lfd.uci.edu/~gohlke/pythonlibs/)2,安装scipy(在同一站点)OK!

For python27 1、Install numpy + mkl(download link:http://www.lfd.uci.edu/~gohlke/pythonlibs/) 2、install scipy (the same site) OK!


回答 9

英特尔现在免费提供用于Linux / Windows / OS X的Python发行版,称为“ 英特尔Python发行版 ”。

它是一个完整的Python发行版(例如,软件包中包含python.exe),其中包括一些根据Intel的MKL(数学内核库)编译的预安装模块,因此针对更快的性能进行了优化。

发行版包括模块NumPy,SciPy,scikit-learn,pandas,matplotlib,Numba,tbb,pyDAAL,Jupyter等。缺点是升级到最新版本的Python有点晚。例如,从今天(2017年5月1日)开始,发行版提供CPython 3.5,而3.6版本已经发布。但是,如果您不需要这些新功能,则应该很好。

Intel now provides a Python distribution for Linux / Windows / OS X for free called “Intel distribution for Python“.

Its a complete Python distribution (e.g. python.exe is included in the package) which includes some pre-installed modules compiled against Intel’s MKL (Math Kernel Library) and thus optimized for faster performance.

The distribution includes the modules NumPy, SciPy, scikit-learn, pandas, matplotlib, Numba, tbb, pyDAAL, Jupyter, and others. The drawback is a bit of lateness in upgrading to more recent versions of Python. For example as of today (1 May 2017) the distribution provides CPython 3.5 while the 3.6 version is already out. But if you don’t need the new features they should be perfectly fine.


回答 10

安装scikit-fuzzy时我也遇到了同样的错误。我解决了如下错误:

  1. 安装Whl文件Numpy
  2. 安装Scipy,再次是whl文件

根据python版本选择文件,例如python3的amd64和python27的其他win32文件

  1. 然后 pip install --user skfuzzy

我希望,它将为您工作

I was also getting same error while installing scikit-fuzzy. I resolved error as follows:

  1. Install Numpy, a whl file
  2. Install Scipy, again a whl file

choose file according to python version like amd64 for python3 and other win32 file for the python27

  1. then pip install --user skfuzzy

I hope, It will work for you


回答 11

解决方案:

  1. 如许多答案中所指定,请从http://www.lfd.uci.edu/~gohlke/pythonlibs/下载NumPySciPy whl 并安装

    pip install <whl_location>
  2. 从源代码构建BLAS / LAPACK

  3. 使用Miniconda

参考:

  1. ScikitLearn安装
  2. 为scipy安装BLAS和LAPACK的最简单方法?

Solutions:

  1. As specified in many answers, download NumPy and SciPy whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/ and install with

    pip install <whl_location>
    
  2. Building BLAS/LAPACK from source

  3. Using Miniconda.

Refer:

  1. ScikitLearn Installation
  2. Easiest way to install BLAS and LAPACK for scipy?

回答 12

使用http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy上的资源 可以解决此问题。但是,您应该注意版本兼容性。经过几次尝试,最终我决定卸载python,然后与numpy一起安装了新版本的python,然后安装了scipy,这解决了我的问题。

Using resources at http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy will solve the problem. However, you should be careful about versions compatibility. After trying for several times, finally I decided to uninstall python and then installed a fresh version of python along with numpy and then installed scipy and this resolved my problem.


回答 13

安装python的intel发行版https://software.intel.com/zh-cn/intel-distribution-for-python

更好的python发行版应首先包含它们

install intel’s distribution of python https://software.intel.com/en-us/intel-distribution-for-python

better of for distribution of python should contain them initially


回答 14

这样做,它为我解决了 pip install -U scikit-learn

do this, it solved for me pip install -U scikit-learn


如何找到Windows上Python的安装位置?

问题:如何找到Windows上Python的安装位置?

我想找出Windows上的Python安装路径。例如:

C:\Python25

如何找到Python的安装位置?

I want to find out my Python installation path on Windows. For example:

C:\Python25

How can I find where Python is installed?


回答 0

在您的Python解释器中,键入以下命令:

>>> import os
>>> import sys
>>> os.path.dirname(sys.executable)
'C:\\Python25'

In your Python interpreter, type the following commands:

>>> import os
>>> import sys
>>> os.path.dirname(sys.executable)
'C:\\Python25'

Also, you can club all these and use a single line command. Open cmd and enter following command

python -c "import os, sys; print(os.path.dirname(sys.executable))"

回答 1

如果您的环境变量中包含python,则可以在cmd中使用以下命令:

>>>其中python

或用于unix环境

>>>哪个python

命令行图片

If you have python in your enviroment variable then you can use the following command in cmd:

>>> where python

or for unix enviroment

>>> which python

command line image


回答 2

可能是

  • C:\ Python36
  • C:\ Users \(您登录的用户)\ AppData \ Local \ Programs \ Python \ Python36

It would be either of

  • C:\Python36
  • C:\Users\(Your logged in User)\AppData\Local\Programs\Python\Python36

回答 3

如果您需要了解Windows 的安装路径而不启动python解释器,请查看Windows注册表。

每个安装的Python版本在以下任一位置都有一个注册表项:

  • HKLM\SOFTWARE\Python\PythonCore\versionnumber\InstallPath
  • HKCU\SOFTWARE\Python\PythonCore\versionnumber\InstallPath

在64位Windows中,它将位于Wow6432Node密钥下:

  • HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\versionnumber\InstallPath

If you need to know the installed path under Windows without starting the python interpreter, have a look in the Windows registry.

Each installed Python version will have a registry key in either:

  • HKLM\SOFTWARE\Python\PythonCore\versionnumber\InstallPath
  • HKCU\SOFTWARE\Python\PythonCore\versionnumber\InstallPath

In 64-bit Windows, it will be under the Wow6432Node key:

  • HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\versionnumber\InstallPath

回答 4

在Windows安装上,我得到以下结果:

>>> import sys
>>> sys.executable
'C:\\Python26\\python.exe'
>>> sys.platform
'win32'
>>>

(您也可以寻找sys.path合理的位置。)

On my windows installation, I get these results:

>>> import sys
>>> sys.executable
'C:\\Python26\\python.exe'
>>> sys.platform
'win32'
>>>

(You can also look in sys.path for reasonable locations.)


回答 5

sys软件包中,您可以找到有关安装的许多有用信息:

import sys
print sys.executable
print sys.exec_prefix

我不确定这会在Windows系统上提供什么,但是在Mac上却executable指向Python二进制文件和exec_prefix安装根目录。

您也可以尝试使用以下方法检查sys模块:

import sys
for k,v in sys.__dict__.items():
    if not callable(v):
        print "%20s: %s" % (k,repr(v))

In the sys package, you can find a lot of useful information about your installation:

import sys
print sys.executable
print sys.exec_prefix

I’m not sure what this will give on your Windows system, but on my Mac executable points to the Python binary and exec_prefix to the installation root.

You could also try this for inspecting your sys module:

import sys
for k,v in sys.__dict__.items():
    if not callable(v):
        print "%20s: %s" % (k,repr(v))

回答 6

如果您想要安装成功后的路径,请先打开CMD并输入python或python -i

它将为您打开交互式外壳,然后键入

导入系统

可执行文件

点击Enter键,您将获得安装Python的路径…

If You want the Path After successful installation then first open you CMD and type python or python -i

It Will Open interactive shell for You and Then type

import sys

sys.executable

Hit enter and you will get path where your python is installed …


回答 7

简单的方法是

1) open CMD
2) type >>where python

Simple way is

1) open CMD
2) type >>where python

回答 8

您可以搜索“您帐户的环境变量”。如果您在路径中添加了Python,那么它将在您的环境变量帐户中显示为“路径”。

但几乎总是可以在“ C:\ Users \%User_name%\ AppData \ Local \ Programs \ Python \ Python_version ”中找到它

AppData ”文件夹可能已隐藏,从工具栏的“ 视图”部分可见。

You can search for the “environmental variable for you account”. If you have added the Python in the path, it’ll show as “path” in your environmental variable account.

but almost always you will find it in “C:\Users\%User_name%\AppData\Local\Programs\Python\Python_version

the ‘AppData‘ folder may be hidden, make it visible from the view section of toolbar.


回答 9

要知道Python的安装位置,可以where python在cmd.exe中执行。

To know where Python is installed you can execute where python in your cmd.exe.


回答 10

如果有人需要在C#中执行此操作,请使用以下代码:

static string GetPythonExecutablePath(int major = 3)
{
    var software = "SOFTWARE";
    var key = Registry.CurrentUser.OpenSubKey(software);
    if (key == null)
        key = Registry.LocalMachine.OpenSubKey(software);
    if (key == null)
        return null;

    var pythonCoreKey = key.OpenSubKey(@"Python\PythonCore");
    if (pythonCoreKey == null)
        pythonCoreKey = key.OpenSubKey(@"Wow6432Node\Python\PythonCore");
    if (pythonCoreKey == null)
        return null;

    var pythonVersionRegex = new Regex("^" + major + @"\.(\d+)-(\d+)$");
    var targetVersion = pythonCoreKey.GetSubKeyNames().
                                        Select(n => pythonVersionRegex.Match(n)).
                                        Where(m => m.Success).
                                        OrderByDescending(m => int.Parse(m.Groups[1].Value)).
                                        ThenByDescending(m => int.Parse(m.Groups[2].Value)).
                                        Select(m => m.Groups[0].Value).First();

    var installPathKey = pythonCoreKey.OpenSubKey(targetVersion + @"\InstallPath");
    if (installPathKey == null)
        return null;

    return (string)installPathKey.GetValue("ExecutablePath");
}

If anyone needs to do this in C# I’m using the following code:

static string GetPythonExecutablePath(int major = 3)
{
    var software = "SOFTWARE";
    var key = Registry.CurrentUser.OpenSubKey(software);
    if (key == null)
        key = Registry.LocalMachine.OpenSubKey(software);
    if (key == null)
        return null;

    var pythonCoreKey = key.OpenSubKey(@"Python\PythonCore");
    if (pythonCoreKey == null)
        pythonCoreKey = key.OpenSubKey(@"Wow6432Node\Python\PythonCore");
    if (pythonCoreKey == null)
        return null;

    var pythonVersionRegex = new Regex("^" + major + @"\.(\d+)-(\d+)$");
    var targetVersion = pythonCoreKey.GetSubKeyNames().
                                        Select(n => pythonVersionRegex.Match(n)).
                                        Where(m => m.Success).
                                        OrderByDescending(m => int.Parse(m.Groups[1].Value)).
                                        ThenByDescending(m => int.Parse(m.Groups[2].Value)).
                                        Select(m => m.Groups[0].Value).First();

    var installPathKey = pythonCoreKey.OpenSubKey(targetVersion + @"\InstallPath");
    if (installPathKey == null)
        return null;

    return (string)installPathKey.GetValue("ExecutablePath");
}

回答 11

如果不存在,请转到C:\ Users \ USER \ AppData \ Local \ Programs \ Python \ Python36,然后通过Windows + ^ R打开控制台,然后键入cmd并按Enter键键入python(如果安装在本地文件中)将显示其版本从那里输入以下import os import sys os.path.dirname(sys.executable)

Go to C:\Users\USER\AppData\Local\Programs\Python\Python36 if it is not there then open console by windows+^R Then type cmd and hit enter type python if installed in your local file it will show you its version from there type the following import os import sys os.path.dirname(sys.executable)


回答 12

如果您已经py安装了命令(可能已安装),则只需使用--list-paths命令的参数即可:

py --list-paths

输出示例:

py Launcher对于Windows
-3.8-32 C:\ Users \ cscott \ AppData \ Local \ Programs \ Python \ Python38-32 \ python.exe *
-2.7-64 C:\ Python27 \ python.exe 找到的已安装Python

*表示使用该py命令执行的脚本的当前活动版本。

If you have the py command installed, which you likely do, then just use the --list-paths argument to the command:

py --list-paths

Example output:

Installed Pythons found by py Launcher for Windows
-3.8-32 C:\Users\cscott\AppData\Local\Programs\Python\Python38-32\python.exe *
-2.7-64 C:\Python27\python.exe

The * indicates the currently active version for scripts executed using the py command.


回答 13

这对我有用: C:\Users\Your_user_name\AppData\Local\Programs\Python

我当前安装的python version3.7.0

希望这可以帮助!

This worked for me: C:\Users\Your_user_name\AppData\Local\Programs\Python

My currently installed python version is 3.7.0

Hope this helps!


回答 14

一般而言

‘C:\ Users \用户名\ AppData \ Local \ Programs \ Python \ Python-version’

或尝试使用(在cmd中)

哪里python

Its generally

‘C:\Users\user-name\AppData\Local\Programs\Python\Python-version’

or try using (in cmd )

where python


回答 15

如果您仍然卡住或得到这个

C:\\\Users\\\name of your\\\AppData\\\Local\\\Programs\\\Python\\\Python36

只需将2替换为1

C:\Users\akshay\AppData\Local\Programs\Python\Python36

if you still stuck or you get this

C:\\\Users\\\name of your\\\AppData\\\Local\\\Programs\\\Python\\\Python36

simply do this replace 2 \ with one

C:\Users\akshay\AppData\Local\Programs\Python\Python36

回答 16

我安装了2和3,发现3时遇到了相同的问题。幸运的是,在Windows路径中键入path可以让我找到安装它的位置。安装刚忘记的Python时,路径是一个选项。如果在安装Python 3时未选择设置路径,则可能无法使用-除非在安装时手动更新了路径。就我而言,它位于c:\ Program Files \ Python37 \ python.exe

I installed 2 and 3 and had the same problem finding 3. Fortunately, typing path at the windows path let me find where I had installed it. The path was an option when I installed Python which I just forgot. If you didn’t select setting the path when you installed Python 3 that probably won’t work – unless you manually updated the path when you installed it. In my case it was at c:\Program Files\Python37\python.exe


回答 17

如果anaconda navigator在Windows上使用,也可以enviornments在环境上滚动,该root环境将指示其安装位置。当您需要将此环境连接到要在其中集成一些python代码的其他应用程序时,可以使用该环境。

If you use anaconda navigator on windows, you can go too enviornments and scroll over the enviornments, the root enviorment will indicate where it is installed. It can help if you want to use this enviorment when you need to connect this to other applications, where you want to integrate some python code.


我可以在同一台Windows计算机上安装Python 3.x和2.x吗?

问题:我可以在同一台Windows计算机上安装Python 3.x和2.x吗?

我正在运行Windows,并且在命令行上运行程序时,shell / OS将根据注册表设置自动运行Python。如果我在同一台计算机上安装2.x和3.x版本的Python,这会中断吗?

我想玩Python 3,同时仍然能够在同一台机器上运行2.x脚本。

I’m running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?

I want to play with Python 3 while still being able to run 2.x scripts on the same machine.


回答 0

共存的官方解决方案似乎是WindowsPython Launcher,PEP 397,它包含在Python 3.3.0中。将发行版转储文件py.exepyw.exe启动器安装到%SYSTEMROOT%C:\Windows)中,然后分别与pypyw脚本关联。

为了使用新启动器(无需手动设置自己的关联),请保持“注册扩展名”选项处于启用状态。我不太确定为什么,但是在我的机器上,它保留了Py 2.7作为(启动器的)“默认”值。

通过直接从命令行调用脚本来运行脚本,这些脚本将通过启动程序进行路由并解析shebang(如果存在)。您还可以显式调用启动器并使用开关:py -3 mypy2script.py

各种各样的shebangs似乎都可以工作

  • #!C:\Python33\python.exe
  • #!python3
  • #!/usr/bin/env python3

以及肆意滥用

  • #! notepad.exe

The official solution for coexistence seems to be the Python Launcher for Windows, PEP 397 which was included in Python 3.3.0. Installing the release dumps py.exe and pyw.exe launchers into %SYSTEMROOT% (C:\Windows) which is then associated with py and pyw scripts, respectively.

In order to use the new launcher (without manually setting up your own associations to it), leave the “Register Extensions” option enabled. I’m not quite sure why, but on my machine it left Py 2.7 as the “default” (of the launcher).

Running scripts by calling them directly from the command line will route them through the launcher and parse the shebang (if it exists). You can also explicitly call the launcher and use switches: py -3 mypy2script.py.

All manner of shebangs seem to work

  • #!C:\Python33\python.exe
  • #!python3
  • #!/usr/bin/env python3

as well as wanton abuses

  • #! notepad.exe

回答 1

这是我的设置:

  1. 使用Windows安装程序安装Python 2.7和3.4 。
  2. 转到C:\Python34(默认安装路径)并将python.exe更改为python3.exe
  3. 编辑 环境变量以包括C:\Python27\;C:\Python27\Scripts\;C:\Python34\;C:\Python34\Scripts\;

现在在命令行中,您可以使用python2.7和python33.4。

Here’s my setup:

  1. Install both Python 2.7 and 3.4 with the windows installers.
  2. Go to C:\Python34 (the default install path) and change python.exe to python3.exe
  3. Edit your environment variables to include C:\Python27\;C:\Python27\Scripts\;C:\Python34\;C:\Python34\Scripts\;

Now in command line you can use python for 2.7 and python3 for 3.4.


回答 2

您可以同时安装。

您应该在脚本之前编写以下代码:

#!/bin/env python2.7

或者,最终…

#!/bin/env python3.6

更新资料

Google上进行快速搜索后,我的解决方案与Unix完美搭配,这是Windows解决方案:

#!c:/Python/python3_6.exe -u

同样的事情:在脚本之前。

You can have both installed.

You should write this in front of your script:

#!/bin/env python2.7

or, eventually…

#!/bin/env python3.6

Update

My solution works perfectly with Unix, after a quick search on Google, here is the Windows solution:

#!c:/Python/python3_6.exe -u

Same thing: in front of your script.


回答 3

从3.3版开始,Python引入了适用于Windows的Launcher实用程序https://docs.python.org/3/using/windows.html#python-launcher-for-windows

为了能够使用多个版本的Python:

  1. 安装Python 2.x(x是您需要的任何版本)
  2. 安装Python 3.x(x是您需要的任何版本,您还必须拥有一个3.x> = 3.3的版本)
  3. 打开命令提示符
  4. 键入py -2.x以启动Python 2.x
  5. 键入py -3.x启动Python 3.x

From version 3.3 Python introduced Launcher for Windows utility https://docs.python.org/3/using/windows.html#python-launcher-for-windows.

So to be able to use multiple versions of Python:

  1. install Python 2.x (x is any version you need)
  2. install Python 3.x (x is any version you need also you have to have one version 3.x >= 3.3)
  3. open Command Prompt
  4. type py -2.x to launch Python 2.x
  5. type py -3.x to launch Python 3.x

回答 4

我从外壳程序中使用2.5、2.6和3.0,以及以下形式的一行批处理脚本:

:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*

命名它们pythonX.Y.bat并将它们放在PATH中的某个位置。将首选的次要版本(即最新版本)的文件复制到pythonX.bat。(例如copy python2.6.bat python2.bat。)然后您可以python2 file.py在任何地方使用。

但是,这没有帮助甚至影响Windows文件关联的情况。为此,您需要一个启动器程序来读取该#!行,然后将其与.py和.pyw文件关联。

I’m using 2.5, 2.6, and 3.0 from the shell with one line batch scripts of the form:

:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*

Name them pythonX.Y.bat and put them somewhere in your PATH. Copy the file for the preferred minor version (i.e. the latest) to pythonX.bat. (E.g. copy python2.6.bat python2.bat.) Then you can use python2 file.py from anywhere.

However, this doesn’t help or even affect the Windows file association situation. For that you’ll need a launcher program that reads the #! line, and then associate that with .py and .pyw files.


回答 5

将两者都添加到环境变量时,将发生冲突,因为两个可执行文件具有相同的名称:python.exe

只需重命名其中之一即可。就我而言,我将其重命名为python3.exe

因此,当我运行python它将执行python.exe2.7,而当我运行python3将执行python3.exe3.6

When you add both to environment variables there will a be a conflict because the two executable have the same name: python.exe.

Just rename one of them. In my case I renamed it to python3.exe.

So when I run python it will execute python.exe which is 2.7 and when I run python3 it will execute python3.exe which is 3.6


回答 6

干得好…

winpylaunch.py

#
# Looks for a directive in the form: #! C:\Python30\python.exe
# The directive must start with #! and contain ".exe".
# This will be assumed to be the correct python interpreter to
# use to run the script ON WINDOWS. If no interpreter is
# found then the script will be run with 'python.exe'.
# ie: whatever one is found on the path.
# For example, in a script which is saved as utf-8 and which
# runs on Linux and Windows and uses the Python 2.6 interpreter...
#
#    #!/usr/bin/python
#    #!C:\Python26\python.exe
#    # -*- coding: utf-8 -*-
#
# When run on Linux, Linux uses the /usr/bin/python. When run
# on Windows using winpylaunch.py it uses C:\Python26\python.exe.
#
# To set up the association add this to the registry...
#
#    HKEY_CLASSES_ROOT\Python.File\shell\open\command
#    (Default) REG_SZ = "C:\Python30\python.exe" S:\usr\bin\winpylaunch.py "%1" %*
#
# NOTE: winpylaunch.py itself works with either 2.6 and 3.0. Once
# this entry has been added python files can be run on the
# commandline and the use of winpylaunch.py will be transparent.
#

import subprocess
import sys

USAGE = """
USAGE: winpylaunch.py <script.py> [arg1] [arg2...]
"""

if __name__ == "__main__":
  if len(sys.argv) > 1:
    script = sys.argv[1]
    args   = sys.argv[2:]
    if script.endswith(".py"):
      interpreter = "python.exe" # Default to wherever it is found on the path.
      lines = open(script).readlines()
      for line in lines:
        if line.startswith("#!") and line.find(".exe") != -1:
          interpreter = line[2:].strip()
          break
      process = subprocess.Popen([interpreter] + [script] + args)
      process.wait()
      sys.exit()
  print(USAGE)

我刚刚在阅读此线程时就搞定了(因为这也是我所需要的)。我在Ubuntu和Windows上都有Python 2.6.1和3.0.1。如果对您不起作用,请在此处发布修复程序。

Here you go…

winpylaunch.py

#
# Looks for a directive in the form: #! C:\Python30\python.exe
# The directive must start with #! and contain ".exe".
# This will be assumed to be the correct python interpreter to
# use to run the script ON WINDOWS. If no interpreter is
# found then the script will be run with 'python.exe'.
# ie: whatever one is found on the path.
# For example, in a script which is saved as utf-8 and which
# runs on Linux and Windows and uses the Python 2.6 interpreter...
#
#    #!/usr/bin/python
#    #!C:\Python26\python.exe
#    # -*- coding: utf-8 -*-
#
# When run on Linux, Linux uses the /usr/bin/python. When run
# on Windows using winpylaunch.py it uses C:\Python26\python.exe.
#
# To set up the association add this to the registry...
#
#    HKEY_CLASSES_ROOT\Python.File\shell\open\command
#    (Default) REG_SZ = "C:\Python30\python.exe" S:\usr\bin\winpylaunch.py "%1" %*
#
# NOTE: winpylaunch.py itself works with either 2.6 and 3.0. Once
# this entry has been added python files can be run on the
# commandline and the use of winpylaunch.py will be transparent.
#

import subprocess
import sys

USAGE = """
USAGE: winpylaunch.py <script.py> [arg1] [arg2...]
"""

if __name__ == "__main__":
  if len(sys.argv) > 1:
    script = sys.argv[1]
    args   = sys.argv[2:]
    if script.endswith(".py"):
      interpreter = "python.exe" # Default to wherever it is found on the path.
      lines = open(script).readlines()
      for line in lines:
        if line.startswith("#!") and line.find(".exe") != -1:
          interpreter = line[2:].strip()
          break
      process = subprocess.Popen([interpreter] + [script] + args)
      process.wait()
      sys.exit()
  print(USAGE)

I’ve just knocked this up on reading this thread (because it’s what I was needing too). I have Pythons 2.6.1 and 3.0.1 on both Ubuntu and Windows. If it doesn’t work for you post fixes here.


回答 7

据我所知,Python使用PATH变量而不是注册表设置来从命令行运行。

因此,如果您在PATH上指向正确的版本,则将使用该版本。请记住,重新启动命令提示符以使用新的PATH设置。

As far as I know Python runs off of the commandline using the PATH variable as opposed to a registry setting.

So if you point to the correct version on your PATH you will use that. Remember to restart your command prompt to use the new PATH settings.


回答 8

Python安装通常会将.py.pyw.pyc文件与Python解释器相关联。因此,您可以通过在资源管理器中双击Python脚本或在命令行窗口中键入其名称来运行Python脚本(这样就无需键入python scriptname.py,就scriptname.py可以了)。

如果要手动更改此关联,则可以在Windows注册表中编辑以下项:

HKEY_CLASSES_ROOT\Python.File\shell\open\command
HKEY_CLASSES_ROOT\Python.NoConFile\shell\open\command
HKEY_CLASSES_ROOT\Python.CompiledFile\shell\open\command

Python启动器

人们一直在研究Windows的Python启动器:与.py.pyw文件相关联的轻量级程序,它将在第一行中寻找“ shebang”行(类似于Linux等),并以2.x或3.x版本启动Python。需要。有关详细信息,请参见“适用于Windows的Python启动器”博客文章。

The Python installation normally associates .py, .pyw and .pyc files with the Python interpreter. So you can run a Python script either by double-clicking it in Explorer or by typing its name in a command-line window (so no need to type python scriptname.py, just scriptname.py will do).

If you want to manually change this association, you can edit these keys in the Windows registry:

HKEY_CLASSES_ROOT\Python.File\shell\open\command
HKEY_CLASSES_ROOT\Python.NoConFile\shell\open\command
HKEY_CLASSES_ROOT\Python.CompiledFile\shell\open\command

Python Launcher

People have been working on a Python launcher for Windows: a lightweight program associated with .py and .pyw files which would look for a “shebang” line (similar to Linux et al) on the first line, and launch Python 2.x or 3.x as required. See “A Python Launcher for Windows” blog post for details.


回答 9

尝试使用Anaconda。

假设使用Anaconda环境的概念,您需要Python 3来学习编程,但是您不想通过更新Python来消灭Python 2.7环境。您可以创建并激活名为“ snakes”(或所需的任何名称)的新环境,并按如下所示安装最新版本的Python 3:

conda create --name snakes python=3

它比听起来简单,请在此处查看介绍页面:Anaconda入门

然后要解决并排运行2.x和3.x版本的特定问题,请参阅:使用Anaconda管理Python版本

Try using Anaconda.

Using the concept of Anaconda environments, let’s say you need Python 3 to learn programming, but you don’t want to wipe out your Python 2.7 environment by updating Python. You can create and activate a new environment named “snakes” (or whatever you want), and install the latest version of Python 3 as follows:

conda create --name snakes python=3

Its simpler than it sounds, take a look at the intro page here: Getting Started with Anaconda

And then to handle your specific problem of having version 2.x and 3.x running side by side, see:


回答 10

这是在同一台机器上运行Python 2和3的方法

  1. 安装Python 2.x
  2. 安装Python 3.x
  3. 启动Powershell
  4. 输入Python -2以启动Python 2.x
  5. 输入Python -3启动Python 2.x

WindowsPython启动器自3.3版开始嵌入到Python中,正如2011年Stand Stand首次亮相时所承诺的那样:

适用于Windows的Python启动器

Here is how to run Python 2 and 3 on the same machine

  1. install Python 2.x
  2. install Python 3.x
  3. Start Powershell
  4. Type Python -2 to launch Python 2.x
  5. Type Python -3 to launch Python 2.x

The Python Launcher for Windows was embedded into Python since Version 3.3, as promised in 2011 when the Stand alone first made its debut:

Python Launcher for Windows


回答 11

这是在Windows上安装Python2和Python3的一种简洁方法。

https://datascience.com.co/how-to-install-python-2-7-and-3-6-in-windows-10-add-python-path-281e7eae62a

我的情况:我必须安装Apache cassandra。我已经在D:驱动器中安装了Python3 。随着大量开发工作的进行,我不想弄乱我的Python3安装。而且,我只需要Python2用于Apache cassandra。

所以我采取了以下步骤:

  1. 下载并安装了Python2。
  2. 已将Python2条目添加到类路径(C:\Python27;C:\Python27\Scripts
  3. python.exe修改为python2.exe(如下图所示)

  1. 现在我可以同时运行两者。适用于Python 2(python2 --version)和Python 3(python --version)。

因此,我的Python3安装保持不变。

Here is a neat and clean way to install Python2 & Python3 on windows.

https://datascience.com.co/how-to-install-python-2-7-and-3-6-in-windows-10-add-python-path-281e7eae62a

My case: I had to install Apache cassandra. I already had Python3 installed in my D: drive. With loads of development work under process i didn’t wanted to mess my Python3 installation. And, i needed Python2 only for Apache cassandra.

So i took following steps:

  1. Downloaded & Installed Python2.
  2. Added Python2 entries to classpath (C:\Python27;C:\Python27\Scripts)
  3. Modified python.exe to python2.exe (as shown in image below)

  1. Now i am able to run both. For Python 2(python2 --version) & Python 3 (python --version).

So, my Python3 installation remained intact.


回答 12

我认为可以在安装程序中为.py文件设置Windows文件关联。取消选中它就可以了。

如果没有,您可以轻松地将.py文件与以前的版本重新关联。最简单的方法是右键单击.py文件,选择“打开方式” /“选择程序”。在出现的对话框中,选择或浏览到默认情况下要使用的python版本,然后选中“始终使用此程序打开这种文件”复选框。

I think there is an option to setup the windows file association for .py files in the installer. Uncheck it and you should be fine.

If not, you can easily re-associate .py files with the previous version. The simplest way is to right click on a .py file, select “open with” / “choose program”. On the dialog that appears, select or browse to the version of python you want to use by default, and check the “always use this program to open this kind of file” checkbox.


回答 13

您应该确保PATH环境变量不包含两个python.exe文件(添加您当前用于每天运行脚本的文件),或按照批处理文件的建议进行操作。除此之外,我不明白为什么不这样。

PS:我安装了2.6作为“主要” python,安装了3.0作为“ play” python。2.6包含在PATH中。一切正常。

You should make sure that the PATH environment variable doesn’t contain both python.exe files ( add the one you’re currently using to run scripts on a day to day basis ) , or do as Kniht suggested with the batch files . Aside from that , I don’t see why not .

P.S : I have 2.6 installed as my “primary” python and 3.0 as my “play” python . The 2.6 is included in the PATH . Everything works fine .


回答 14

在我勇敢地同时安装两者之前,我有很多问题。如果我给python,我要py2时会转到py3吗?pip / virtualenv是否会在py2 / 3下发生?

现在看来非常简单。

只需盲目安装它们。确保您获得正确的类型(x64 / x32)。在安装时/安装后,请确保添加到环境变量的路径。

[ENVIRONMENT]::SETENVIRONMENTVARIABLE("PATH", "$ENV:PATH;C:\PYTHONx", "USER")

替换上面命令中的x以设置路径。

然后转到两个文件夹。

导航

python3.6/Scripts/

并将pip重命名为pip3。

如果pip3已经存在,请删除该pip。这将确保just pip将在python2下运行。您可以通过以下方式进行验证:

pip --version

如果您想在python3中使用pip,请使用

pip3 install 

您可以类似地对python文件和其他文件执行相同的操作。

干杯!

Before I courageously installed both simultaneously, I had so many questions. If I give python will it go to py3 when i want py2? pip/virtualenv will happen under py2/3?

It seems to be very simple now.

Just blindly install both of them. Make sure you get the right type(x64/x32). While/after installing make sure you add to the path to your environment variables.

[ENVIRONMENT]::SETENVIRONMENTVARIABLE("PATH", "$ENV:PATH;C:\PYTHONx", "USER")

Replace the x in the command above to set the path.

Then go to both the folders.

Navigate to

python3.6/Scripts/

and rename pip to pip3.

If pip3 already exists delete the pip. This will make sure that just pip will run under python2. You can verify by:

pip --version

In case you want to use pip with python3 then just use

pip3 install 

You can similarly do the same to python file and others.

Cheers!


回答 15

Easy-peasy,在安装了两个python版本之后,将路径添加到环境变量;请参阅。然后转到python 2和python 3文件夹,分别将它们重命名为python2和python3,如图和所示。现在在cmd中键入python2或python3以使用所需的版本,请参见

Easy-peasy ,after installing both the python versions add the paths to the environment variables ;see. Then go to python 2 and python 3 folders and rename them to python2 and python3 respectively as shown and . Now in cmd type python2 or python3 to use your required version see .


回答 16

我假设是这样,我在同一台计算机上并排安装了Python 2.4、2.5和2.6。

I would assume so, I have Python 2.4, 2.5 and 2.6 installed side-by-side on the same computer.


回答 17

我现在刚开始使用python。我正在阅读Zed Shaw的书“以困难的方式学习Python”,该书需要python 2.x版本,但同时也要学习一个需要python 3.x的类。

这就是我所做的。

  1. 下载python 2.7
  2. 运行电源外壳(应该已经在Windows上安装)
  3. 在POWERSHELL中运行python(如果无法识别,请转到步骤4)
  4. 仅当powershell无法识别python 2.7时,才输入以下内容:

“ [[环境] :: SETENVIRONMENTVARIABLE(“ PATH”,“ $ ENV:PATH; C:\ PYTHON27”,“ USER”)“(无外部引号)

  1. 现在键入python,您应该看到它说python 2.7等等等等

现在适用于python 3.x

简单,适用于Windows应用程序的python 3.x下载带有python。因此,只需将适用于Windows的Python应用程序固定到任务栏,或创建桌面快捷方式即可完成!

打开适用于Windows的3.x版Python

打开适用于python 2.x的Powershell

我希望这有帮助!

I am just starting out with python now. I’m reading Zed Shaw’s book “Learn Python the Hard Way” which requires python version 2.x but am also taking a class that requires python 3.x

So here is what I did.

  1. Download python 2.7
  2. run power shell (should already be installed on windows)
  3. run python IN POWERSHELL (if it doesn’t recognize then go to step 4)
  4. Only if powershell doesn’t recognize python 2.7 type in the following:

“[ENVIRONMENT]::SETENVIRONMENTVARIABLE(“PATH”, “$ENV:PATH;C:\PYTHON27”, “USER”)” (no outside quotes)

  1. Now type python and you should see it say python 2.7 blah blah blah

NOW for python 3.x

Simple, python 3.x download comes with python for windows app. SO simply pin the Python for Windows app to your task bar, or create shortcut to the desktop and you are done!

Open Python for Windows for 3.x

Open Powershell for python 2.x

I hope this helps!


回答 18

嗯..我现在通过在https://www.python.org/downloads/release/python-365/下载适用于Windows的Python 3.6.5来做到这一点,并确保将安装启动器。然后,我按照使用python 2和python 3的说明进行操作。重新启动命令提示符,然后使用py -2.7来使用Python 2和pypy -3.6来使用Python3。您还可以将其pip2用于Python 2 pippipPython 3 pip

Hmm..I did this right now by just downloading Python 3.6.5 for Windows at https://www.python.org/downloads/release/python-365/ and made sure that the launcher would be installed. Then, I followed the instructions for using python 2 and python 3. Restart the command prompt and then use py -2.7 to use Python 2 and py or py -3.6 to use Python 3. You can also use pip2 for Python 2’s pip and pip for Python 3’s pip.


回答 19

我在要使用python3进行大多数工作时遇到了同样的问题,但是IDA pro需要python2。所以,这就是我所做的。

我首先在用户环境变量中创建了3个变量,如下所示:

  1. PYTHON_ACTIVE:最初为空
  2. HOME_PYTHON27:具有安装Python 2的文件夹的路径。例如。“; /脚本;”
  3. HOME_PYTHON38:类似于python 2,此变量包含python 3文件夹的路径。

现在我加了

%PYTHON_ACTIVE%

到PATH变量。因此,基本上说这个“ PYTHON_ACTIVE”包含的内容就是活动的python。我们以编程方式更改“ PYTHON_ACTIVE”的包含内容以切换python版本。

这是示例脚本:

:: This batch file is used to switch between python 2 and 3.
@ECHO OFF

set /p choice= "Please enter '27' for python 2.7 , '38' for python 3.8 : "

IF %choice%==27 (
setx PYTHON_ACTIVE %HOME_PYTHON27%
)

IF %choice%==38 (
setx PYTHON_ACTIVE %HOME_PYTHON38%
)


PAUSE

该脚本将python版本作为输入,并因此将HOME_PYTHON27或HOME_PYTHON38复制到PYTHON_ACTIVE。从而更改了全局Python版本。

I had the same problem where I wanted to use python3 for most work but IDA pro required python2. SO, here’s what I did.

I first created 3 variables in the user environment variable as follows:

  1. PYTHON_ACTIVE : This is initially empty
  2. HOME_PYTHON27 : Has a path to a folder where Python 2 is installed. Eg. “;/scripts;”
  3. HOME_PYTHON38 : Similar to python 2, this variable contains a path to python 3 folders.

Now I added

%PYTHON_ACTIVE%

to PATH variable. So, basically saying that whatever this “PYTHON_ACTIVE” contains is the active python. We programmatically change the contains of “PYTHON_ACTIVE” to switch python version.

Here is the example script:

:: This batch file is used to switch between python 2 and 3.
@ECHO OFF

set /p choice= "Please enter '27' for python 2.7 , '38' for python 3.8 : "

IF %choice%==27 (
setx PYTHON_ACTIVE %HOME_PYTHON27%
)

IF %choice%==38 (
setx PYTHON_ACTIVE %HOME_PYTHON38%
)


PAUSE

This script takes python version as input and accordingly copies HOME_PYTHON27 or HOME_PYTHON38 to PYTHON_ACTIVE. Thus changing the global Python version.


如何在Windows上安装PyCrypto?

问题:如何在Windows上安装PyCrypto?

我已经阅读了所有其他Google来源和SO线程,但没有任何效果。

Python 2.7.3 32bit安装在上Windows 7 64bit。下载,解压缩然后尝试在以下位置安装PyCrypto结果"Unable to find vcvarsall.bat".

因此,我安装了MinGW,并将其作为选择的编译器安装在安装线上。但是然后我得到了错误"RuntimeError: chmod error".

我该如何解决这个问题?我试过使用pip,它给出相同的结果。我找到了一个预构建的PyCrypto 2.3二进制文件并进行了安装,但是在系统上找不到该文件(无法正常工作)。

有任何想法吗?

I’ve read every other google source and SO thread, with nothing working.

Python 2.7.3 32bit installed on Windows 7 64bit. Download, extracting, and then trying to install PyCrypto results in "Unable to find vcvarsall.bat".

So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error "RuntimeError: chmod error".

How in the world do I get around this? I’ve tried using pip, which gives the same result. I found a prebuilt PyCrypto 2.3 binary and installed that, but it’s nowhere to be found on the system (not working).

Any ideas?


回答 0

如果尚未安装与Python.org分发的Visual Studio二进制文件兼容的C / C ++开发环境,则应坚持仅安装纯Python软件包或可用于Windows二进制文件的软件包。

幸运的是,有适用于Windows的PyCrypto二进制文件:http ://www.voidspace.org.uk/python/modules.shtml#pycrypto

更新:
正如@Udi在下面的注释中建议的那样,以下命令也将安装pycrypto并可以在其中使用virtualenv

easy_install http://www.voidspace.org.uk/python/pycrypto-2.6.1/pycrypto-2.6.1.win32-py2.7.exe

注意,请从此列表中选择与您的设置相关的链接

如果您正在寻找适用于Python 3.5的版本,请参阅python 3.5上的PyCrypto

If you don’t already have a C/C++ development environment installed that is compatible with the Visual Studio binaries distributed by Python.org, then you should stick to installing only pure Python packages or packages for which a Windows binary is available.

Fortunately, there are PyCrypto binaries available for Windows: http://www.voidspace.org.uk/python/modules.shtml#pycrypto

UPDATE:
As @Udi suggests in the comment below, the following command also installs pycrypto and can be used in virtualenv as well:

easy_install http://www.voidspace.org.uk/python/pycrypto-2.6.1/pycrypto-2.6.1.win32-py2.7.exe

Notice to choose the relevant link for your setup from this list

If you’re looking for builds for Python 3.5, see PyCrypto on python 3.5


回答 1

Microsoft最近最近发布了用于Python 2.7的独立的专用Microsoft Visual C ++编译器。如果您使用的是Python 2.7,只需安装该编译器和Setuptools 6.0或更高版本,大多数具有C扩展名的软件包现在都可以轻松编译。

Microsoft has recently recently released a standalone, dedicated Microsoft Visual C++ Compiler for Python 2.7. If you’re using Python 2.7, simply install that compiler and Setuptools 6.0 or later, and most packages with C extensions will now compile readily.


回答 2

经过数年之久,python终于同意了一种二进制发行版wheel,该发行版允许在Windows上安装甚至二进制扩展,而无需使用简单的编译器pip install packagename。有一种流行的软件包列表及其状态。Pycrypto还不存在,例如lxml,PySide和Scrapy。

2015年11月编辑pip uninstall pycryptopip install pycryptodome。这是pycrypto具有新功能的前叉,并且支持车轮。它取代了pycrypto,因此现有代码将继续起作用(请参阅https://pycryptodome.readthedocs.org/en/latest/src/examples.html

After years and years, python finally agreed for a binary disribution called wheel which allows to install even binary extensions on Windows without having a compiler with simple pip install packagename. There is a list of popular packages with their status. Pycrypto is not there yet, but lxml, PySide and Scrapy for example.

Edited Nov 2015: pip uninstall pycrypto & pip install pycryptodome. It is a pycrypto fork with new features and it supports wheel. It replaces pycrypto, so existing code will continue to work (see https://pycryptodome.readthedocs.org/en/latest/src/examples.html)


回答 3

对于VS2010:

SET VS90COMNTOOLS=%VS100COMNTOOLS%

对于VS2012:

SET VS90COMNTOOLS=%VS110COMNTOOLS%

然后调用:

pip install pyCrypto 

For VS2010:

SET VS90COMNTOOLS=%VS100COMNTOOLS%

For VS2012:

SET VS90COMNTOOLS=%VS110COMNTOOLS%

then Call:

pip install pyCrypto 

回答 4

一般来说

vcvarsall.bat是Visual C ++编译器的一部分,您需要安装要安装的内容。如果您的Python是使用Visual Studio工具链编译的,甚至不要尝试处理MingGW,反之亦然。甚至Microsoft工具链的版本也很重要。用VS 2008编译的Python不能与用VS 2010编译的扩展一起使用!

您必须使用与Python版本相同的编译器来编译PyCrypto。Google的“无法找到vcvarsall.bat”,因为这是问题的根源,这是在Windows上编译Python扩展的一个非常普遍的问题。

在使用此链接的任何系统上,要获得正确的信息,都需要大量的信息和大量的阅读。

注意使用Visual Studio 2010或不使用Visual Studio 2008

据我所知,以下仍然是正确的。这是在2010年6月的链接中发布的,该链接是指尝试针对python.org上可用的Python安装程序使用VS 2010 Express构建扩展。

如果这样做,请小心。python.org的Python 2.6和2.7是使用Visual Studio 2008编译器构建的。您将需要使用与Python相同的CRT(msvcr90.dll)进行链接。

Visual Studio 2010 Express链接到错误的CRT版本:msvcr100.dll。

如果执行此操作,则还必须使用Visual Studio 2010 Express重新构建Python。您不能将标准的Python二进制安装程序用于Windows。您也不能使用使用与Visual Studio 2010(Express)不同的编译器构建的任何C / C ++扩展。

意见:这是我放弃Windows从事OSX的所有重要开发工作的原因之一!

In general

vcvarsall.bat is part of the Visual C++ compiler, you need that to install what you are trying to install. Don’t even try to deal with MingGW if your Python was compiled with Visual Studio toolchain and vice versa. Even the version of the Microsoft tool chain is important. Python compiled with VS 2008 won’t work with extensions compiled with VS 2010!

You have to compile PyCrypto with the same compiler that the version of Python was compiled with. Google for “Unable to find vcvarsall.bat” because that is the root of your problem, it is a very common problem with compiling Python extensions on Windows.

There is a lot of information and a lot to read to get this right on whatever system you are on with this link.

Beware using Visual Studio 2010 or not using Visual Studio 2008

As far as I know the following is still true. This was posted in the link above in June, 2010 referring to trying to build extensions with VS 2010 Express against the Python installers available on python.org.

Be careful if you do this. Python 2.6 and 2.7 from python.org are built with Visual Studio 2008 compilers. You will need to link with the same CRT (msvcr90.dll) as Python.

Visual Studio 2010 Express links with the wrong CRT version: msvcr100.dll.

If you do this, you must also re-build Python with Visual Studio 2010 Express. You cannot use the standard Python binary installer for Windows. Nor can you use any C/C++ extensions built with a different compiler than Visual Studio 2010 (Express).

Opinion: This is one reason I abandoned Windows for all serious development work for OSX!


回答 5

PyCryptodomePyCrypto的几乎兼容的分支,带有pypi上的Windows轮子。

您可以使用以下简单的方法安装它:

pip install pycryptodome

该网站还包含使用Microsoft编译器从源进行构建的说明。

PyCryptodome is an almost-compatible fork of PyCrypto with Windows wheels available on pypi.

You can install it with a simple:

pip install pycryptodome

The website includes instructions to build it from sources with the Microsoft compilers too.


回答 6

我设法pycrypto通过使用MinGW32和进行编译MSYS。假定您已安装pipeasy_install安装。

这是我的做法:

1)安装MinGW32。为了便于说明,我们假设它已安装在中C:\MinGW。我建议使用安装程序时,选择. MSYS应该随其一起安装的C ++编译器MinGW

2)添加c:\mingw\bin,c:\mingw\mingw32\bin,C:\MinGW\msys\1.0, c:\mingw\msys\1.0\bin and c:\mingw\msys\1.0\sbin到您的中%PATH%。如果您不熟悉,这篇文章会很有帮助。

3)从搜索栏中运行msys,然后MSYS终端将打开。对于熟悉的人Cygwin,它的工作方式类似。

4)pip install pycrypto在此之后,应从MSYS终端内部正常运行。

I have managed to get pycrypto to compile by using MinGW32 and MSYS. This presumes that you have pip or easy_install installed.

Here’s how I did it:

1) Install MinGW32. For the sake of this explanation, let’s assume it’s installed in C:\MinGW. When using the installer, which I recommend, select the C++ compiler. MSYS should install with MinGW

2) Add c:\mingw\bin,c:\mingw\mingw32\bin,C:\MinGW\msys\1.0, c:\mingw\msys\1.0\bin and c:\mingw\msys\1.0\sbin to your %PATH%. If you aren’t familiar, this article is very helpful.

3) From the search bar, run msys and the MSYS terminal will open. For those familiar with Cygwin, it works in a similar fashion.

4) From within the MSYS terminal pip install pycrypto should run without error after this.


回答 7

对于Windows 7:

要在Windows中安装Pycrypto,

在命令提示符中尝试此操作,

设置路径= C:\ Python27 \ Scripts(即easy_install所在的路径)

然后执行以下命令

easy_install pycrypto

对于Ubuntu:

试试这个,

从“ https://pypi.python.org/pypi/pycrypto ” 下载Pycrypto

然后使用终端将当前路径更改为下载路径,并且用户应为root:

例如:root @ xyz-virtual-machine:〜/ pycrypto-2.6.1#

然后使用终端执行以下命令:

python setup.py安装

对我有用。希望为所有人服务。

For Windows 7:

To install Pycrypto in Windows,

Try this in Command Prompt,

Set path=C:\Python27\Scripts (i.e path where easy_install is located)

Then execute the following,

easy_install pycrypto

For Ubuntu:

Try this,

Download Pycrypto from “https://pypi.python.org/pypi/pycrypto

Then change your current path to downloaded path using your terminal and user should be root:

Eg: root@xyz-virtual-machine:~/pycrypto-2.6.1#

Then execute the following using the terminal:

python setup.py install

It’s worked for me. Hope works for all..


回答 8

对于那些正在寻找python 3.4的人,我发现了一个可以正常使用的安装程序的git repo。这是x64的直接链接x32

For those of you looking for python 3.4 I found a git repo with an installer that just works. Here are the direct links for x64 and x32


回答 9

可以使用Windows 7 SDK工具包构建PyCrypto。Windows 7 SDK有两个版本。原始版本(针对.Net 3.5)包括VS 2008命令行编译器。可以同时安装32位和64位编译器。

第一步是编译mpir以提供快速算法。我已经记录了在gmpy库中使用的过程。可以在sdk_build中找到使用SDK编译器构建mpir的详细说明。

在DOS提示符下使用SDK编译器的关键步骤是:

1)根据需要运行vcvars32.bat或vcvars64.bat。

2)在提示符下,执行“ set MSSdk = 1”

3)在提示符下,执行“ set DISTUTILS_USE_SDK = 1”

假设C代码没有其他问题,这应该可以使“ python setup.py install”成功。但是我模糊地记得我不得不编辑几个PyCrypto文件来启用mpir并找到mpir库,但是目前我没有Windows系统。我将需要几天的时间来重新创建这些步骤。如果您到那时还没有报告成功,我将发布PyCrypto步骤。这些步骤将假定您能够编译mpir。

我希望这有帮助。

It’s possible to build PyCrypto using the Windows 7 SDK toolkits. There are two versions of the Windows 7 SDK. The original version (for .Net 3.5) includes the VS 2008 command-line compilers. Both 32- and 64-bit compilers can be installed.

The first step is to compile mpir to provide fast arithmetic. I’ve documented the process I use in the gmpy library. Detailed instructions for building mpir using the SDK compiler can be found at sdk_build

The key steps to use the SDK compilers from a DOS prompt are:

1) Run either vcvars32.bat or vcvars64.bat as appropriate.

2) At the prompt, execute “set MSSdk=1”

3) At the prompt, execute “set DISTUTILS_USE_SDK=1”

This should allow “python setup.py install” to succeed assuming there are no other issues with the C code. But I vaaguely remember that I had to edit a couple of PyCrypto files to enable mpir and to find the mpir libraries but I don’t have my Windows system up at the moment. It will be a couple of days before I’ll have time to recreate the steps. If you haven’t reported success by then, I’ll post the PyCrypto steps. The steps will assume you were able to compile mpir.

I hope this helps.


回答 10

尝试仅使用:

pip install pycryptodome

要么:

pip install pycryptodomex

来源:https : //pypi.python.org/pypi/pycryptodome

Try just using:

pip install pycryptodome

or:

pip install pycryptodomex

Source: https://pypi.python.org/pypi/pycryptodome


回答 11

因此,我安装了MinGW,并将其作为选择的编译器安装在安装线上。但是,然后我得到错误“ RuntimeError:chmod错误”。

"RuntimeError: chmod error"发生此错误是因为安装脚本找不到chmod命令。

我该如何解决这个问题?

您只需要将MSYS二进制文件添加到PATH并重新运行安装脚本即可

(注意:MinGW随MSYS一起提供)

例如,如果我们在文件夹中 C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1>

C:\.....>set PATH=C:\MinGW\msys\1.0\bin;%PATH%
C:\.....>python setup.py install

可选:在重新运行脚本之前,您可能需要清理:

`C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1> python setup.py clean`

So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error “RuntimeError: chmod error”.

This error "RuntimeError: chmod error" occurs because the install script didn’t find the chmod command.

How in the world do I get around this?

Solution

You only need to add the MSYS binaries to the PATH and re-run the install script.

(N.B: Note that MinGW comes with MSYS so )

Example

For example, if we are in folder C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1>

C:\.....>set PATH=C:\MinGW\msys\1.0\bin;%PATH%
C:\.....>python setup.py install

Optional: you might need to clean before you re-run the script:

`C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1> python setup.py clean`

回答 12

  1. 转到适用于Python 2.7的Microsoft Visual C ++编译器 ”,然后根据“系统要求”继续操作(这是我按照以下步骤进行的工作)。

  2. 安装setuptools(6.0或更高版本需要Python来自动检测setuptools的这个编译器包) 或者通过: pip install setuptools 下载“setuptools的自举安装”源来自于你的filestystem为“ez_python.py”,保存这个文件somwhere与安装:python ez_python.py

  3. 安装滚轮(建议使用滚轮来生产预构建的二进制软件包)。您可以使用以下方法安装它:pip install wheel

  4. 打开Windows提升的命令提示符cmd.exe(带有“以管理员身份运行”),为所有用户安装“适用于Python 2.7的Microsoft Visual C ++编译器”。您可以使用以下命令来执行此操作:msiexec / i C:\users\jozko\download\VCForPython27.msi ALLUSERS=1仅使用您自己的文件路径:msiexec /i <path to MSI> ALLUSERS=1

  5. 现在,您应该能够使用以下命令安装pycrypto: pip install pycrypto

  1. Go to Microsoft Visual C++ Compiler for Python 2.7 and continue based on “System Requirements” (this is what I did to put below steps together).

  2. Install setuptools (setuptools 6.0 or later is required for Python to automatically detect this compiler package) either by: pip install setuptools or download “Setuptools bootstrapping installer” source from, save this file somwhere on your filestystem as “ez_python.py” and install with: python ez_python.py

  3. Install wheel (wheel is recommended for producing pre-built binary packages). You can install it with: pip install wheel

  4. Open Windows elevated Command Prompt cmd.exe (with “Run as administrator”) to install “Microsoft Visual C++ Compiler for Python 2.7” for all users. You can use following command to do so: msiexec /i C:\users\jozko\download\VCForPython27.msi ALLUSERS=1 just use your own path to file: msiexec /i <path to MSI> ALLUSERS=1

  5. Now you should be able to install pycrypto with: pip install pycrypto


回答 13

如果您在Windows上并且正在努力安装Pycrypcto,请使用:pip install pycryptodome。它像奇迹一样运作,比起进行大量的配置和调整将使您的生活更加轻松。

If you are on Windows and struggling with installing Pycrypcto just use the: pip install pycryptodome. It works like a miracle and it will make your life much easier than trying to do a lot of configurations and tweaks.


回答 14

这可能不是最佳解决方案,但是您可以从MS下载并安装免费的Visual C ++ Express软件包。这将为您提供编译PyCrypto代码所需的C ++编译器。

This probably isn’t the optimal solution but you might download and install the free Visual C++ Express package from MS. This will give you the C++ compiler you need to compile the PyCrypto code.


回答 15

我的答案可能与此处提到的问题无关,但是我对Python 3.4遇到了同样的问题,其中Crypto.Cipher不是有效的导入。所以我尝试安装PyCrypto并遇到问题。

经过研究,我发现3.4应该使用pycryptodome

我使用pycharm安装pycryptodome,效果很好。

Crypto.Cipher导入AES

My answer might not be related to problem mention here, but I had same problem with Python 3.4 where Crypto.Cipher wasn’t a valid import. So I tried installing PyCrypto and went into problems.

After some research I found with 3.4 you should use pycryptodome.

I install pycryptodome using pycharm and I was good.

from Crypto.Cipher import AES


回答 16

因此,我安装了MinGW,并将其作为选择的编译器安装在安装线上。但是,然后我得到错误“ RuntimeError:chmod错误”。

您需要在MinGW下安装msys软件包

并在PATH env变量中添加以下条目。

  • C:\MinGW\bin
  • C:\MinGW\msys\1.0\bin [在这里您将找到chmod可执行文件]

然后从正常的Windows命令提示符下运行命令。

So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error “RuntimeError: chmod error”.

You need to install msys package under MinGW

and add following entries in your PATH env variable.

  • C:\MinGW\bin
  • C:\MinGW\msys\1.0\bin [This is where you will find chmod executable]

Then run your command from normal windows command prompt.


回答 17

由于奇怪的法律原因,二进制文件无法正常发布。空隙空间通常是最好的第二个来源。但是由于相当长的一段时间,voidspace维护程序没有更新。使用[ https://www.dropbox.com/s/n6rckn0k6u4nqke/pycrypto-2.6.1.zip?dl=0]中的压缩文件

Due to weird legal reasons, binaries are not published the normal way. Voidspace is normally the best second source. But since quite some time, voidspace maintainer did not update. Use the zip from [https://www.dropbox.com/s/n6rckn0k6u4nqke/pycrypto-2.6.1.zip?dl=0]


回答 18

步骤1:从此处安装Visual C ++ 2010 Express 。

(请勿安装Microsoft Visual Studio 2010 Service Pack 1)

步骤2:从“控制面板\程序和功能”中删除所有Microsoft Visual C ++ 2010可再发行程序包。如果您不这样做,则安装将失败,并显示模糊的“安装过程中出现致命错误”错误。

步骤3:从此处安装用于Visual Studio 2010(v7.1)的Windows SDK的脱机版本。这是64位扩展所必需的。Windows内置了对Pismo等ISO的安装。

步骤4:您需要使用Pismo File Mount Audit Package安装ISO文件。从这里下载Pismo

步骤5:右键单击下载的ISO文件,然后选择Pismo挂载。之后,安装Setup \ SDKSetup.exe而不是setup.exe。

步骤6a:通过将目录更改为C:\ Program Files(x86)\ Microsoft Visual Studio版本\ VC \在C:\ Program Files(x86)\ Microsoft Visual Studio 10.0 \ VC \ bin \ amd64中创建vcvars64.bat文件命令提示符。在命令提示符下键入命令: cd C:\Program Files (x86)\Microsoft Visual Studio version\VC\r

步骤6b:要为针对x86平台的64位命令行构建配置此“命令提示符”窗口,请在命令提示符下输入: vcvarsall x86单击此处以获取更多选项。

步骤7:在命令提示符下,输入以下命令安装PyCrypto: C:\Python3X>pip install -U your_wh_file

Step 1: Install Visual C++ 2010 Express from here.

(Do not install Microsoft Visual Studio 2010 Service Pack 1 )

Step 2: Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don’t do those then the install is going to fail with an obscure “Fatal error during installation” error.

Step 3: Install offline version of Windows SDK for Visual Studio 2010 (v7.1) from here. This is required for 64bit extensions. Windows has builtin mounting for ISOs like Pismo.

Step 4: You need to install the ISO file with Pismo File Mount Audit Package. Download Pismo from here

Step 5: Right click the downloaded ISO file and choose mount with Pismo. Thereafter, install the Setup\SDKSetup.exe instead of setup.exe.

Step 6a: Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 by changing directory to C:\Program Files (x86)\Microsoft Visual Studio version\VC\ on the command prompt. Type command on the command prompt: cd C:\Program Files (x86)\Microsoft Visual Studio version\VC\r

Step 6b: To configure this Command Prompt window for 64-bit command-line builds that target x86 platforms, at the command prompt, enter: vcvarsall x86 Click here for more options.

Step 7: At the command prompt, install the PyCrypto by typing: C:\Python3X>pip install -U your_wh_file


回答 19

我有python的Pycharm。

  1. pycharm -> file -> setting -> project interpreter

  2. 点击 +

  3. 搜索"pycrypto"并安装软件包

注意:如果尚未安装“适用于Python 2.7的Microsoft Visual C ++编译器”,则它将提示安装,一旦安装完成,请尝试上述步骤,即可正常工作。

I had Pycharm for python.

  1. Go to pycharm -> file -> setting -> project interpreter

  2. Click on +

  3. Search for "pycrypto" and install the package

Note: If you don’t have “Microsoft Visual C++ Compiler for Python 2.7” installed then it will prompt for installation, once installation finished try the above steps it should work fine.


如何在Python Shell中知道/更改当前目录?

问题:如何在Python Shell中知道/更改当前目录?

我在Windows 7上使用Python 3.2。打开Python Shell时,如何知道当前目录是什么,以及如何将其更改为模块所在的另一个目录?

I am using Python 3.2 on Windows 7. When I open the Python shell, how can I know what the current directory is and how can I change it to another directory where my modules are?


回答 0

您可以使用该os模块。

>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'

但是,如果要查找其他模块:您可以PYTHONPATH在Linux下设置一个名为的环境变量,就像

export PYTHONPATH=/path/to/my/library:$PYTHONPATH

然后,解释器也在此位置搜索imported模块。我想Windows下的名称会相同,但是不知道如何更改。

编辑

在Windows下:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(摘自http://docs.python.org/using/windows.html

编辑2

…甚至更好:使用virtualenvvirtualenv_wrapper,这将允许您创建一个开发环境,在其中您可以根据需要添加模块路径(add2virtualenv),而不会污染安装或“正常”的工作环境。

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

You can use the os module.

>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'

But if it’s about finding other modules: You can set an environment variable called PYTHONPATH, under Linux would be like

export PYTHONPATH=/path/to/my/library:$PYTHONPATH

Then, the interpreter searches also at this place for imported modules. I guess the name would be the same under Windows, but don’t know how to change.

edit

Under Windows:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(taken from http://docs.python.org/using/windows.html)

edit 2

… and even better: use virtualenv and virtualenv_wrapper, this will allow you to create a development environment where you can add module paths as you like (add2virtualenv) without polluting your installation or “normal” working environment.

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html


回答 1

你要

import os
os.getcwd()
os.chdir('..')

you want

import os
os.getcwd()
os.chdir('..')

回答 2

>>> import os
>>> os.system('cd c:\mydir')

实际上,os.system()可以执行Windows命令提示符可以执行的任何命令,而不仅仅是更改dir。

>>> import os
>>> os.system('cd c:\mydir')

In fact, os.system() can execute any command that windows command prompt can execute, not just change dir.


回答 3

更改当前目录不是处理Python中的模块的方法。

相反,请参阅有关模块搜索路径的文档获取Python如何找到要导入的模块的信息。

以下是“ 标准模块”部分的相关内容:

变量sys.path是一个字符串列表,该字符串确定解释器对模块的搜索路径。它初始化为从环境变量PYTHONPATH提取的默认路径,或者如果未设置PYTHONPATH则从内置的默认路径初始化。您可以使用标准列表操作对其进行修改:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

在回答有关获取和设置当前目录的原始问题时:

>>> help(os.getcwd)

getcwd(...)
    getcwd() -> path

    Return a string representing the current working directory.

>>> help(os.chdir)

chdir(...)
    chdir(path)

    Change the current working directory to the specified path.

Changing the current directory is not the way to deal with finding modules in Python.

Rather, see the docs for The Module Search Path for how Python finds which module to import.

Here is a relevant bit from Standard Modules section:

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

In answer your original question about getting and setting the current directory:

>>> help(os.getcwd)

getcwd(...)
    getcwd() -> path

    Return a string representing the current working directory.

>>> help(os.chdir)

chdir(...)
    chdir(path)

    Change the current working directory to the specified path.

回答 4

在python中更改当前工作目录的最简单方法是使用“ os”包。下面是Windows计算机的示例:

# Import the os package
import os

# Confirm the current working directory 
os.getcwd()

# Use '\\' while changing the directory 
os.chdir("C:\\user\\foldername")

The easiest way to change the current working directory in python is using the ‘os’ package. Below there is an example for windows computer:

# Import the os package
import os

# Confirm the current working directory 
os.getcwd()

# Use '\\' while changing the directory 
os.chdir("C:\\user\\foldername")

回答 5

如果您import os可以os.getcwd用来获取当前的工作目录,并且可以os.chdir用来更改目录

If you import os you can use os.getcwd to get the current working directory, and you can use os.chdir to change your directory


回答 6

您可以尝试以下方法:

import os

current_dir = os.path.dirname(os.path.abspath(__file__))   # Can also use os.getcwd()
print(current_dir)                                         # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')                         
print(new_dir)                                             # prints "D:\abc\def\ghi"

You can try this:

import os

current_dir = os.path.dirname(os.path.abspath(__file__))   # Can also use os.getcwd()
print(current_dir)                                         # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')                         
print(new_dir)                                             # prints "D:\abc\def\ghi"



如何保持Python脚本输出窗口打开?

问题:如何保持Python脚本输出窗口打开?

我刚开始使用Python。当我在Windows上执行python脚本文件时,出现输出窗口,但立即消失。我需要它呆在那里,以便我可以分析我的输出。如何保持打开状态?

I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?


回答 0

您有几种选择:

  1. 从已经打开的终端运行程序。打开命令提示符并键入:

    python myscript.py

    为此,您需要在路径中使用python可执行文件。只需检查如何在Windows 上编辑环境变量,然后添加C:\PYTHON26(或安装python的任何目录)即可。

    程序结束后,它将带您回到cmd提示符,而不是关闭窗口。

  2. 添加代码以在脚本末尾等待。对于Python2,添加…

    raw_input()

    …在脚本末尾使其等待Enter键。该方法很烦人,因为您必须修改脚本,并且必须记得在完成后将其删除。测试其他人的脚本时特别烦人。对于Python3,请使用input()

  3. 使用适合您的编辑器。一些为python准备的编辑器将在执行后自动为您暂停。其他编辑器允许您配置用于运行程序的命令行。我发现python -i myscript.py在运行时将其配置为“ ” 特别有用。程序结束后,您将在加载了程序环境的情况下进入python shell,因此您可以进一步使用变量以及调用函数和方法。

You have a few options:

  1. Run the program from an already-open terminal. Open a command prompt and type:

    python myscript.py
    

    For that to work you need the python executable in your path. Just check on how to edit environment variables on Windows, and add C:\PYTHON26 (or whatever directory you installed python to).

    When the program ends, it’ll drop you back to the cmd prompt instead of closing the window.

  2. Add code to wait at the end of your script. For Python2, adding …

    raw_input()
    

    … at the end of the script makes it wait for the Enter key. That method is annoying because you have to modify the script, and have to remember removing it when you’re done. Specially annoying when testing other people’s scripts. For Python3, use input().

  3. Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as “python -i myscript.py” when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods.


回答 1

cmd /k是使用控制台窗口打开任何控制台应用程序(不仅限于Python)的典型方法,该窗口在应用程序关闭后仍将保留。我认为最简单的方法是按Win + R,键入cmd /k,然后将想要的脚本拖放到“运行”对话框中。

cmd /k is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type cmd /k and then drag&drop the script you want to the Run dialog.


回答 2

从已经打开的cmd窗口中启动脚本,或者在脚本末尾添加如下所示的内容,在Python 2中:

 raw_input("Press enter to exit ;)")

或者,在Python 3中:

input("Press enter to exit ;)")

Start the script from already open cmd window or at the end of script add something like this, in Python 2:

 raw_input("Press enter to exit ;)")

Or, in Python 3:

input("Press enter to exit ;)")

回答 3

在出现异常时保持窗口打开(但在打印异常时)

Python 2

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
        print "Press Enter to continue ..." 
        raw_input() 

无论如何要保持窗口打开:

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
    finally:
        print "Press Enter to continue ..." 
        raw_input()

Python 3

对于Python3,您必须使用input()代替raw_input(),当然还要修改print语句。

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except BaseException:
        import sys
        print(sys.exc_info()[0])
        import traceback
        print(traceback.format_exc())
        print("Press Enter to continue ...")
        input() 

无论如何要保持窗口打开:

if __name__ == '__main__':
    try:
        ## your code, typically one function call
except BaseException:
    import sys
    print(sys.exc_info()[0])
    import traceback
    print(traceback.format_exc())
finally:
    print("Press Enter to continue ...")
    input()

To keep your window open in case of exception (yet, while printing the exception)

Python 2

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
        print "Press Enter to continue ..." 
        raw_input() 

To keep the window open in any case:

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
    finally:
        print "Press Enter to continue ..." 
        raw_input()

Python 3

For Python3 you’ll have to use input() in place of raw_input(), and of course adapt the print statements.

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except BaseException:
        import sys
        print(sys.exc_info()[0])
        import traceback
        print(traceback.format_exc())
        print("Press Enter to continue ...")
        input() 

To keep the window open in any case:

if __name__ == '__main__':
    try:
        ## your code, typically one function call
except BaseException:
    import sys
    print(sys.exc_info()[0])
    import traceback
    print(traceback.format_exc())
finally:
    print("Press Enter to continue ...")
    input()

回答 4

您可以在之前合并答案:(对于Notepad ++用户)

按F5运行当前脚本并键入命令:

cmd /k python -i "$(FULL_CURRENT_PATH)"

这样,您在执行Notepad ++ python脚本后就可以保持交互模式,并且可以使用变量等等:)

you can combine the answers before: (for Notepad++ User)

press F5 to run current script and type in command:

cmd /k python -i "$(FULL_CURRENT_PATH)"

in this way you stay in interactive mode after executing your Notepad++ python script and you are able to play around with your variables and so on :)


回答 5

使用以下两行创建Windows批处理文件:

python your-program.py

pause

Create a Windows batch file with these 2 lines:

python your-program.py

pause

回答 6

在python 2中,您可以执行以下操作:raw_input()

>>print("Hello World!")    
>>raw_input('Waiting a key...')

在python 3中,您可以执行以下操作:input()

>>print("Hello world!")    
>>input('Waiting a key...')

另外,您可以使用time.sleep(time)

>>import time
>>print("The program will close in 5 seconds")
>>time.sleep(5)

In python 2 you can do it with: raw_input()

>>print("Hello World!")    
>>raw_input('Waiting a key...')

In python 3 you can do it with: input()

>>print("Hello world!")    
>>input('Waiting a key...')

Also, you can do it with the time.sleep(time)

>>import time
>>print("The program will close in 5 seconds")
>>time.sleep(5)

回答 7

使用atexit,您可以在程序退出时立即暂停它。如果错误/异常是退出的原因,则它将在打印stacktrace后暂停。

import atexit

# Python 2 should use `raw_input` instead of `input`
atexit.register(input, 'Press Enter to continue...')

在我的程序中,我将对的调用atexit.register放在了except子句中,以便仅在出现问题时才会暂停。

if __name__ == "__main__":
    try:
        something_that_may_fail()

    except:
        # Register the pause.
        import atexit
        atexit.register(input, 'Press Enter to continue...')

        raise # Reraise the exception.

Using atexit, you can pause the program right when it exits. If an error/exception is the reason for the exit, it will pause after printing the stacktrace.

import atexit

# Python 2 should use `raw_input` instead of `input`
atexit.register(input, 'Press Enter to continue...')

In my program, I put the call to atexit.register in the except clause, so that it will only pause if something went wrong.

if __name__ == "__main__":
    try:
        something_that_may_fail()

    except:
        # Register the pause.
        import atexit
        atexit.register(input, 'Press Enter to continue...')

        raise # Reraise the exception.

回答 8

我有一个类似的问题。使用Notepad ++时,我曾经使用过命令:C:\Python27\python.exe "$(FULL_CURRENT_PATH)"在代码终止后立即关闭cmd窗口。
现在我正在使用cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)"它来保持cmd窗口打开。

I had a similar problem. With Notepad++ I used to use the command : C:\Python27\python.exe "$(FULL_CURRENT_PATH)" which closed the cmd window immediately after the code terminated.
Now I am using cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)" which keeps the cmd window open.


回答 9

在Python 3上

input('Press Enter to Exit...')

会成功的。

On Python 3

input('Press Enter to Exit...')

Will do the trick.


回答 10

为了保持窗口打开,我同意Anurag的意见,这就是我为简短的小型计算类型程序保持窗口打开的方法。

这只会显示没有文本的光标:

raw_input() 

下一个示例将向您清楚地表明该程序已完成,而不必等待该程序中的另一个输入提示:

print('You have reached the end and the "raw_input()" function is keeping the window open') 
raw_input()

注意!
(1)在python 3中,没有raw_input(),只有 input()
(2)用单引号表示一个字符串;否则,如果您在任何内容(例如“ raw_input()”)附近键入double,它将认为它是函数,变量等,而不是文本。

在下一个示例中,我使用双引号,但由于它认为“ the”和“ function”之间的引号存在中断,所以即使它在您阅读时,您自己的想法也可以完全理解,但它不会起作用:

print("You have reached the end and the "input()" function is keeping the window open")
input()

希望这可以帮助那些可能刚起步但还没有弄清楚计算机如何思考的人。可能要花一点时间。:o)

To just keep the window open I agree with Anurag and this is what I did to keep my windows open for short little calculation type programs.

This would just show a cursor with no text:

raw_input() 

This next example would give you a clear message that the program is done and not waiting on another input prompt within the program:

print('You have reached the end and the "raw_input()" function is keeping the window open') 
raw_input()

Note!
(1) In python 3, there is no raw_input(), just input().
(2) Use single quotes to indicate a string; otherwise if you type doubles around anything, such as “raw_input()”, it will think it is a function, variable, etc, and not text.

In this next example, I use double quotes and it won’t work because it thinks there is a break in the quotes between “the” and “function” even though when you read it, your own mind can make perfect sense of it:

print("You have reached the end and the "input()" function is keeping the window open")
input()

Hopefully this helps others who might be starting out and still haven’t figured out how the computer thinks yet. It can take a while. :o)


回答 11

如果要从桌面快捷方式运行脚本,请右键单击python文件,然后选择Send to|Desktop (create shortcut)。然后右键单击快捷方式,然后选择“属性”。在“快捷方式”选项卡上,选择“目标:”文本框,然后添加cmd /k 到路径的前面,然后单击“确定”。现在,该快捷方式应该可以在不关闭脚本的情况下运行您的脚本,并且您不需要input('Hit enter to close')

请注意,如果您的计算机上有多个版本的python,请在cmd / k和scipt路径之间添加所需python可执行文件的名称,如下所示:

cmd /k python3 "C:\Users\<yourname>\Documents\your_scipt.py"

If you want to run your script from a desktop shortcut, right click your python file and select Send to|Desktop (create shortcut). Then right click the shortcut and select Properties. On the Shortcut tab select the Target: text box and add cmd /k in front of the path and click OK. The shortcut should now run your script without closing and you don’t need the input('Hit enter to close')

Note, if you have more than one version of python on your machine, add the name of the required python executable between cmd /k and the scipt path like this:

cmd /k python3 "C:\Users\<yourname>\Documents\your_scipt.py"

回答 12

除了input和之外raw_input,您还可以使用无限while循环,例如: while True: pass(Python 2.5 + / 3)或while 1: pass(Python 2/3的所有版本)。但是,这可能会使用计算能力。

您也可以从命令行运行程序。python在命令行(Mac OS X Terminal)中键入,然后说Python 3.?.?(您的Python版本)它不会显示您的Python版本,或者说您python: command not found正在研究更改PATH值(上面列出的环境值)/ type C:\(Python folder\python.exe。如果成功,则键入pythonC:\(Python installation)\python.exe和程序的完整目录

Apart from input and raw_input, you could also use an infinite while loop, like this: while True: pass (Python 2.5+/3) or while 1: pass (all versions of Python 2/3). This might use computing power, though.

You could also run the program from the command line. Type python into the command line (Mac OS X Terminal) and it should say Python 3.?.? (Your Python version) It it does not show your Python version, or says python: command not found, look into changing PATH values (enviromentl values, listed above)/type C:\(Python folder\python.exe. If that is successful, type python or C:\(Python installation)\python.exe and the full directory of your program.


回答 13

答案很迟,但是我创建了一个Windows Batch文件pythonbat.bat,该文件包含以下内容:

python.exe %1
@echo off
echo.
pause

然后指定pythonbat.bat.py文件的默认处理程序。

现在,当我.py在文件资源管理器中双击一个文件时,它将打开一个新的控制台窗口,运行Python脚本,然后暂停(保持打开状态),直到按任意键为止。

无需更改任何Python脚本。

我仍然可以打开控制台窗口并指定python myscript.py是否要…

(我刚刚注意到@maurizio已经发布了这个确切答案)

A very belated answer, but I created a Windows Batch file called pythonbat.bat containing the following:

python.exe %1
@echo off
echo.
pause

and then specified pythonbat.bat as the default handler for .py files.

Now, when I double-click a .py file in File Explorer, it opens a new console window, runs the Python script and then pauses (remains open), until I press any key…

No changes required to any Python scripts.

I can still open a console window and specify python myscript.py if I want to…

(I just noticed @maurizio already posted this exact answer)


回答 14

您可以打开PowerShell并键入“ python”。导入Python之后,您可以从您喜欢的文本编辑器中复制粘贴源代码以运行代码。

窗户不会关闭。

You can open PowerShell and type “python”. After Python has been imported, you can copy paste the source code from your favourite text-editor to run the code.

The window won’t close.


回答 15

如果要保持cmd窗口打开并位于运行文件目录中,则可以在Windows 10上运行:

cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)

If you want to stay cmd-window open AND be in running-file directory this works at Windows 10:

cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)

回答 16

我在win10的py3环境中发现的解决方案只是以Administrator身份运行cmd或powershell,并且输出将保留在同一控制台窗口中,任何其他类型的用户运行python命令都将导致python打开一个新的控制台窗口。

I found the solution on my py3 enviroment at win10 is just run cmd or powershell as Administrator,and the output would stay at the same console window,any other type of user run python command would cause python to open a new console window.


回答 17

  1. 这里下载并安装Notepad ++
  2. 这里下载并安装Python 2.7 not 3。
  3. 启动,运行Powershell。输入以下内容。 [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
  4. 关闭Powershell并重新打开它。
  5. 为您的程序创建目录。mkdir脚本
  6. 打开该目录的cd脚本
  7. 在记事本++中,在新文件类型中: print "hello world"
  8. 将文件另存为hello.py
  9. 返回powershell并通过输入dir确保您在正确的目录中。您应该在那里看到文件hello.py。
  10. 在Powershell提示符下键入: python hello.py
  1. Go here and download and install Notepad++
  2. Go here and download and install Python 2.7 not 3.
  3. Start, Run Powershell. Enter the following. [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
  4. Close Powershell and reopen it.
  5. Make a directory for your programs. mkdir scripts
  6. Open that directory cd scripts
  7. In Notepad++, in a new file type: print "hello world"
  8. Save the file as hello.py
  9. Go back to powershell and make sure you are in the right directory by typing dir. You should see your file hello.py there.
  10. At the Powershell prompt type: python hello.py

回答 18

保持窗口打开的简单技巧:

counter = 0

While (True):

    If (counter == 0):

        # Code goes here

    counter += 1

计数器是这样,因此代码不会重复自身。

A simple hack to keep the window open:

counter = 0

While (True):

    If (counter == 0):

        # Code goes here

    counter += 1

The counter is so the code won’t repeat itself.


回答 19

最简单的方法:

import time

#Your code here
time.sleep(60)
#end of code (and console shut down)

这将使代码保留1分钟,然后将其关闭。

The simplest way:

import time

#Your code here
time.sleep(60)
#end of code (and console shut down)

this will leave the code up for 1 minute then close it.


回答 20

在Windows 10上插入以下代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

奇怪,但是对我有用!(当然,最后还有input())

On windows 10 insert at beggining this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Strange, but it work for me!(Together with input() at the end, of course)