标签归档:mysql-python

Python mysqldb:库未加载:libmysqlclient.18.dylib

问题:Python mysqldb:库未加载:libmysqlclient.18.dylib

我刚刚在Mac OS 10.6上为python 2.7编译并安装了mysqldb。我创建了一个简单的测试文件,可以导入

import MySQLdb as mysql

首先,此命令带有红色下划线,并且信息告诉我“未解决的导入”。然后我尝试运行以下简单的python代码

import MySQLdb as mysql

def main():
    conn = mysql.connect( charset="utf8", use_unicode=True, host="localhost",user="root", passwd="",db="" )

if __name__ == '__main__'():
    main()

执行它时,我收到以下错误消息

Traceback (most recent call last):
  File "/path/to/project/Python/src/cvdv/TestMySQLdb.py", line 4, in <module>
    import MySQLdb as mysql
  File "build/bdist.macosx-10.6-intel/egg/MySQLdb/__init__.py", line 19, in <module>
    \namespace cvdv
  File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 7, in <module>
  File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so
  Reason: image not found

解决我的问题的方法可能是什么?

编辑:实际上我发现该库位于/ usr / local / mysql / lib中。所以我需要告诉我的pydev eclipse版本在哪里找到它。我在哪里设置?

I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I created a simple test file that imports

import MySQLdb as mysql

Firstly, this command is red underlined and the info tells me “Unresolved import”. Then I tried to run the following simple python code

import MySQLdb as mysql

def main():
    conn = mysql.connect( charset="utf8", use_unicode=True, host="localhost",user="root", passwd="",db="" )

if __name__ == '__main__'():
    main()

When executing it I get the following error message

Traceback (most recent call last):
  File "/path/to/project/Python/src/cvdv/TestMySQLdb.py", line 4, in <module>
    import MySQLdb as mysql
  File "build/bdist.macosx-10.6-intel/egg/MySQLdb/__init__.py", line 19, in <module>
    \namespace cvdv
  File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 7, in <module>
  File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so
  Reason: image not found

What might be the solution to my problem?

EDIT: Actually I found out that the library lies in /usr/local/mysql/lib. So I need to tell my pydev eclipse version where to find it. Where do I set this?


回答 0

我通过创建到库的符号链接解决了这个问题。即

实际的库位于

/usr/local/mysql/lib

然后我在其中创建了一个符号链接

/usr/lib

使用命令:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

这样我就具有以下映射:

ls -l libmysqlclient.18.dylib 
lrwxr-xr-x  1 root  wheel  44 16 Jul 14:01 libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib

就是这样 之后,一切正常。

编辑:

请注意,自MacOS El Capitan以来,系统完整性保护(SIP,也称为“无根”)将阻止您在中创建链接/usr/lib/。您可以按照以下说明禁用SIP ,但可以在其中创建链接/usr/local/lib/

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

I solved the problem by creating a symbolic link to the library. I.e.

The actual library resides in

/usr/local/mysql/lib

And then I created a symbolic link in

/usr/lib

Using the command:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

so that I have the following mapping:

ls -l libmysqlclient.18.dylib 
lrwxr-xr-x  1 root  wheel  44 16 Jul 14:01 libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib

That was it. After that everything worked fine.

EDIT:

Notice, that since MacOS El Capitan the System Integrity Protection (SIP, also known as “rootless”) will prevent you from creating links in /usr/lib/. You could disable SIP by following these instructions, but you can create a link in /usr/local/lib/ instead:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

用None替换Pandas或Numpy Nan以与MysqlDB一起使用

问题:用None替换Pandas或Numpy Nan以与MysqlDB一起使用

我正在尝试使用MysqlDB将Pandas数据帧(或可以使用numpy数组)写入mysql数据库。MysqlDB似乎不理解’nan’,我的数据库抛出一个错误,说nan不在字段列表中。我需要找到一种将’nan’转换为NoneType的方法。

有任何想法吗?

I am trying to write a Pandas dataframe (or can use a numpy array) to a mysql database using MysqlDB . MysqlDB doesn’t seem understand ‘nan’ and my database throws out an error saying nan is not in the field list. I need to find a way to convert the ‘nan’ into a NoneType.

Any ideas?


回答 0

@bogatron正确,您可以使用where,值得注意的是您可以在熊猫本机执行此操作:

df1 = df.where(pd.notnull(df), None)

注意:这会将所有列的dtype更改为object

例:

In [1]: df = pd.DataFrame([1, np.nan])

In [2]: df
Out[2]: 
    0
0   1
1 NaN

In [3]: df1 = df.where(pd.notnull(df), None)

In [4]: df1
Out[4]: 
      0
0     1
1  None

注意:您不能执行的操作dtype是使用astype,然后使用DataFrame fillna方法来重铸DataFrame 以允许所有数据类型,请执行以下操作:

df1 = df.astype(object).replace(np.nan, 'None')

遗憾的是这个没有,也没有使用replace,用作品None这个(关闭)的问题


顺便说一句,值得注意的是,对于大多数用例,您不需要将NaN替换为None,请参阅有关熊猫中NaN和None之间的区别的问题。

但是,在这种特定情况下,您似乎可以这样做(至少在回答此问题时)。

@bogatron has it right, you can use where, it’s worth noting that you can do this natively in pandas:

df1 = df.where(pd.notnull(df), None)

Note: this changes the dtype of all columns to object.

Example:

In [1]: df = pd.DataFrame([1, np.nan])

In [2]: df
Out[2]: 
    0
0   1
1 NaN

In [3]: df1 = df.where(pd.notnull(df), None)

In [4]: df1
Out[4]: 
      0
0     1
1  None

Note: what you cannot do recast the DataFrames dtype to allow all datatypes types, using astype, and then the DataFrame fillna method:

df1 = df.astype(object).replace(np.nan, 'None')

Unfortunately neither this, nor using replace, works with None see this (closed) issue.


As an aside, it’s worth noting that for most use cases you don’t need to replace NaN with None, see this question about the difference between NaN and None in pandas.

However, in this specific case it seems you do (at least at the time of this answer).


回答 1

df = df.replace({np.nan: None})

这个Github问题归功于这个家伙。

df = df.replace({np.nan: None})

Credit goes to this guy here on this Github issue.


回答 2

您可以在numpy数组中替换nanNone

>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>

You can replace nan with None in your numpy array:

>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>

回答 3

经过绊脚,这对我有用:

df = df.astype(object).where(pd.notnull(df),None)

After stumbling around, this worked for me:

df = df.astype(object).where(pd.notnull(df),None)

回答 4

只是@Andy Hayden的答案的补充:

由于DataFrame.mask是的相对孪生子DataFrame.where,因此它们具有完全相同的签名,但含义相反:

  • DataFrame.where对于替换条件为False的很有用
  • DataFrame.mask用于替换条件为True的值。

所以在这个问题上,使用df.mask(df.isna(), other=None, inplace=True)可能会更直观。

Just an addition to @Andy Hayden’s answer:

Since DataFrame.mask is the opposite twin of DataFrame.where, they have the exactly same signature but with opposite meaning:

  • DataFrame.where is useful for Replacing values where the condition is False.
  • DataFrame.mask is used for Replacing values where the condition is True.

So in this question, using df.mask(df.isna(), other=None, inplace=True) might be more intuitive.


回答 5

另外除了:更换倍数和转换从柱背面的类型时要小心对象浮动。如果您想确定自己None的不会退回到np.NaN‘s’,请使用@ andy-hayden的建议pd.where。替换仍然会出错的说明:

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: df = pd.DataFrame({"a": [1, np.NAN, np.inf]})

In [4]: df
Out[4]:
     a
0  1.0
1  NaN
2  inf

In [5]: df.replace({np.NAN: None})
Out[5]:
      a
0     1
1  None
2   inf

In [6]: df.replace({np.NAN: None, np.inf: None})
Out[6]:
     a
0  1.0
1  NaN
2  NaN

In [7]: df.where((pd.notnull(df)), None).replace({np.inf: None})
Out[7]:
     a
0  1.0
1  NaN
2  NaN

Another addition: be careful when replacing multiples and converting the type of the column back from object to float. If you want to be certain that your None‘s won’t flip back to np.NaN‘s apply @andy-hayden’s suggestion with using pd.where. Illustration of how replace can still go ‘wrong’:

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: df = pd.DataFrame({"a": [1, np.NAN, np.inf]})

In [4]: df
Out[4]:
     a
0  1.0
1  NaN
2  inf

In [5]: df.replace({np.NAN: None})
Out[5]:
      a
0     1
1  None
2   inf

In [6]: df.replace({np.NAN: None, np.inf: None})
Out[6]:
     a
0  1.0
1  NaN
2  NaN

In [7]: df.where((pd.notnull(df)), None).replace({np.inf: None})
Out[7]:
     a
0  1.0
1  NaN
2  NaN

回答 6

很老,但我偶然发现了同样的问题。尝试这样做:

df['col_replaced'] = df['col_with_npnans'].apply(lambda x: None if np.isnan(x) else x)

Quite old, yet I stumbled upon the very same issue. Try doing this:

df['col_replaced'] = df['col_with_npnans'].apply(lambda x: None if np.isnan(x) else x)

ImportError:没有名为MySQLdb的模块

问题:ImportError:没有名为MySQLdb的模块

我指的是以下教程来为我的Web应用程序创建登录页面。 http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out–net-29982

我的数据库有问题。我正在

ImportError: No module named MySQLdb

当我执行

http://127.0.0.1:5000/testdb

我已经尝试了所有可能的方法来安装python mysql,这是本教程中提到的一种,easy_install,sudo apt-get install。

我已经在虚拟环境中安装了mysql。我的目录结构与本教程中说明的目录结构相同。该模块已成功安装在我的系统中,但仍然出现此错误。

请帮忙。是什么原因造成的。

I am referring the following tutorial to make a login page for my web application. http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out–net-29982

I am having issue with the database. I am getting an

ImportError: No module named MySQLdb

when I execute

http://127.0.0.1:5000/testdb

I have tried all possible ways to install python mysql, the one mentioned in the tutorial, easy_install, sudo apt-get install.

I have installed mysql in my virtual env. My directory structure is just the same as whats explained in the tutorial. The module is sucessfully installed in my system and still I am getting this error.

Please help. What could be causing this.


回答 0

如果您在编译二进制扩展名时遇到问题,或者在无法扩展的平台上,则可以尝试使用纯python PyMySQL绑定。

只需pip install pymysql切换您的SQLAlchemy URI即可,如下所示:

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://.....'

您还可以尝试其他一些驱动程序

If you’re having issues compiling the binary extension, or on a platform where you cant, you can try using the pure python PyMySQL bindings.

Simply pip install pymysql and switch your SQLAlchemy URI to start like this:

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://.....'

There are some other drivers you could also try.


回答 1

或尝试以下方法:

apt-get install python-mysqldb

Or try this:

apt-get install python-mysqldb

回答 2

你可以尝试

pip install mysqlclient

may you try

pip install mysqlclient

回答 3

我的问题是:

return __import__('MySQLdb')
ImportError: No module named MySQLdb

和我的决议:

pip install MySQL-python
yum install mysql-devel.x86_64

在开始的时候,我刚刚安装了MySQL-python,但是问题仍然存在。因此,我认为如果发生此问题,您还应该考虑mysql-devel。希望这可以帮助。

My issue is :

return __import__('MySQLdb')
ImportError: No module named MySQLdb

and my resolution :

pip install MySQL-python
yum install mysql-devel.x86_64

at the very beginning, i just installed MySQL-python, but the issue still existed. So i think if this issue happened, you should also take mysql-devel into consideration. Hope this helps.


回答 4

在研究SQLAlchemy时遇到了这个问题。SQLAlchemy用于MySQL的默认方言是mysql+mysqldb

engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')

No module named MySQLdb执行上述命令时出现“ ”错误。要修复它,我安装了mysql-python模块,此问题已解决。

sudo pip install mysql-python

I got this issue when I was working on SQLAlchemy. The default dialect used by SQLAlchemy for MySQL is mysql+mysqldb.

engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')

I got the “No module named MySQLdb” error when the above command was executed. To fix it I installed the mysql-python module and the issue was fixed.

sudo pip install mysql-python

回答 5

根据我的经验,它也取决于Python版本。

如果您使用的是Python 3,则@DazWorrall答案对我来说效果很好。

但是,如果您使用的是Python 2,则应该

sudo pip install mysql-python

这将安装“ MySQLdb”模块,而无需更改SQLAlchemy URI。

It depends on Python Version as well in my experience.

If you are using Python 3, @DazWorrall answer worked fine for me.

However, if you are using Python 2, you should

sudo pip install mysql-python

which would install ‘MySQLdb’ module without having to change the SQLAlchemy URI.


回答 6

所以我花了大约5个小时试图弄清楚在尝试运行时如何处理此问题

./manage.py makemigrations

使用Ubuntu Server LTS 16.1,完整的LAMP堆栈,Apache2 MySql 5.7 PHP 7 Python 3和Django 1.10.2,我确实很难找到一个好的答案。实际上,我仍然不满意,但是对我有用的唯一解决方案是……

sudo apt-get install build-essential python-dev libapache2-mod-wsgi-py3 libmysqlclient-dev

其次(从虚拟环境内部)

pip install mysqlclient

我真的不喜欢在尝试设置新的Web服务器时必须使用dev install,但是不幸的是,这种配置是我唯一可以采用的舒适方式。

So I spent about 5 hours trying to figure out how to deal with this issue when trying to run

./manage.py makemigrations

With Ubuntu Server LTS 16.1, a full LAMP stack, Apache2 MySql 5.7 PHP 7 Python 3 and Django 1.10.2 I really struggled to find a good answer to this. In fact, I am still not satisfied, but the ONLY solution that worked for me is this…

sudo apt-get install build-essential python-dev libapache2-mod-wsgi-py3 libmysqlclient-dev

followed by (from inside the virtual environment)

pip install mysqlclient

I really dislike having to use dev installs when I am trying to set up a new web server, but unfortunately this configuration was the only mostly comfortable path I could take.


回答 7

尽管@Edward van Kuik答案是正确的,但并未考虑virtualenv v1.7及更高版本的问题

特别是在Ubuntu 上python-mysqldb通过via apt进行安装时,将其放在下/usr/lib/pythonX.Y/dist-packages,但virtualenv的默认情况下不包含此路径。sys.path

因此,要解决此问题,您应该通过运行类似以下内容的系统包来创建您的virtualenv:

virtualenv --system-site-packages .venv

While @Edward van Kuik‘s answer is correct, it doesn’t take into account an issue with virtualenv v1.7 and above.

In particular installing python-mysqldb via apt on Ubuntu put it under /usr/lib/pythonX.Y/dist-packages, but this path isn’t included by default in the virtualenv’s sys.path.

So to resolve this, you should create your virtualenv with system packages by running something like:

virtualenv --system-site-packages .venv


回答 8

有太多与权限有关的错误,什么也没有。您可能想试试这个:

xcode-select --install

Got so many errors related to permissions and what not. You may wanna try this :

xcode-select --install

回答 9

yum install MySQL-python.x86_64

为我工作。

yum install MySQL-python.x86_64

worked for me.


回答 10

在ubuntu 20中,您可以尝试以下操作:

sudo apt-get install libmysqlclient-dev
sudo apt-get install gcc
pip install mysqlclient

In ubuntu 20 , you can try this :

sudo apt-get install libmysqlclient-dev
sudo apt-get install gcc
pip install mysqlclient

导入模块中全局变量的可见性

问题:导入模块中全局变量的可见性

我在使用Python脚本导入模块时遇到了一些麻烦。我将尽力描述错误,为什么会遇到错误以及为什么要使用这种特殊方法来解决我的问题(我将在稍后描述):

假设我有一个模块,其中定义了一些实用程序函数/类,这些函数/类引用在此辅助模块将导入到的命名空间中定义的实体(让“ a”是这样的实体):

模块1:

def f():
    print a

然后,我有了主程序,其中定义了“ a”,我要将这些实用程序导入其中:

import module1
a=3
module1.f()

执行该程序将触发以下错误:

Traceback (most recent call last):
  File "Z:\Python\main.py", line 10, in <module>
    module1.f()
  File "Z:\Python\module1.py", line 3, in f
    print a
NameError: global name 'a' is not defined

过去(两天前,d’uh)曾提出类似的问题,并提出了几种解决方案,但是我真的不认为这些符合我的要求。这是我的特定情况:

我正在尝试制作一个Python程序,该程序连接到MySQL数据库服务器并使用GUI显示/修改数据。为了简洁起见,我在一个单独的文件中定义了一堆与MySQL相关的辅助/实用程序功能。但是它们都有一个公共变量,该变量是我最初实用程序模块中定义的,并且是MySQLdb模块中的游标对象。后来我意识到,游标对象(用于与db服务器通信的对象)应该在主模块中定义,以便主模块和导入到其中的所有对象都可以访问该对象。

最终结果将是这样的:

utilities_module.py:

def utility_1(args):
    code which references a variable named "cur"
def utility_n(args):
    etcetera

而我的主要模块:

program.py:

import MySQLdb, Tkinter
db=MySQLdb.connect(#blahblah) ; cur=db.cursor()  #cur is defined!
from utilities_module import *

然后,一旦我尝试调用任何实用程序函数,就会触发上述“未定义全局名称”错误。

一个特别的建议是在实用程序文件中有一个“ from program import cur”语句,例如:

utilities_module.py:

from program import cur
#rest of function definitions

program.py:

import Tkinter, MySQLdb
db=MySQLdb.connect(#blahblah) ; cur=db.cursor()  #cur is defined!
from utilities_module import *

但这是循环导入或类似的操作,最重要的是,它也崩溃了。所以我的问题是:

我该如何在主模块中定义的“ cur”对象对导入到其中的辅助功能可见?

如果您将解决方案发布在其他位置,则感谢您的宝贵时间和最深切的歉意。我只是自己找不到答案,而且我的书中没有其他花招。

I’ve run into a bit of a wall importing modules in a Python script. I’ll do my best to describe the error, why I run into it, and why I’m tying this particular approach to solve my problem (which I will describe in a second):

Let’s suppose I have a module in which I’ve defined some utility functions/classes, which refer to entities defined in the namespace into which this auxiliary module will be imported (let “a” be such an entity):

module1:

def f():
    print a

And then I have the main program, where “a” is defined, into which I want to import those utilities:

import module1
a=3
module1.f()

Executing the program will trigger the following error:

Traceback (most recent call last):
  File "Z:\Python\main.py", line 10, in <module>
    module1.f()
  File "Z:\Python\module1.py", line 3, in f
    print a
NameError: global name 'a' is not defined

Similar questions have been asked in the past (two days ago, d’uh) and several solutions have been suggested, however I don’t really think these fit my requirements. Here’s my particular context:

I’m trying to make a Python program which connects to a MySQL database server and displays/modifies data with a GUI. For cleanliness sake, I’ve defined the bunch of auxiliary/utility MySQL-related functions in a separate file. However they all have a common variable, which I had originally defined inside the utilities module, and which is the cursor object from MySQLdb module. I later realised that the cursor object (which is used to communicate with the db server) should be defined in the main module, so that both the main module and anything that is imported into it can access that object.

End result would be something like this:

utilities_module.py:

def utility_1(args):
    code which references a variable named "cur"
def utility_n(args):
    etcetera

And my main module:

program.py:

import MySQLdb, Tkinter
db=MySQLdb.connect(#blahblah) ; cur=db.cursor()  #cur is defined!
from utilities_module import *

And then, as soon as I try to call any of the utilities functions, it triggers the aforementioned “global name not defined” error.

A particular suggestion was to have a “from program import cur” statement in the utilities file, such as this:

utilities_module.py:

from program import cur
#rest of function definitions

program.py:

import Tkinter, MySQLdb
db=MySQLdb.connect(#blahblah) ; cur=db.cursor()  #cur is defined!
from utilities_module import *

But that’s cyclic import or something like that and, bottom line, it crashes too. So my question is:

How in hell can I make the “cur” object, defined in the main module, visible to those auxiliary functions which are imported into it?

Thanks for your time and my deepest apologies if the solution has been posted elsewhere. I just can’t find the answer myself and I’ve got no more tricks in my book.


回答 0

Python中的全局变量是模块的全局变量,而不是所有模块的全局变量。(许多人对此感到困惑,因为在C语言中,除非您明确创建全局变量,否则所有实现文件中的全局变量都是相同的static。)

有多种解决方法,具体取决于您的实际用例。


在走这条路之前,请问自己这是否真的需要是全球性的。也许您真的想要一个带有f实例方法的类,而不仅仅是一个自由函数?然后,您可以执行以下操作:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

如果您确实确实想要一个全局变量,但是它只是供您使用module1,请在该模块中进行设置。

import module1
module1.a=3
module1.f()

另一方面,如果a由许多模块共享,则将其放置在其他位置,并让每个人都将其导入:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

…并且,在module1.py中:

import shared_stuff
def f():
    print shared_stuff.a

from除非变量打算是一个常量,否则不要使用导入。from shared_stuff import a会创建一个新a变量,初始化为shared_stuff.a导入时所引用的变量,并且该新a变量将不受分配的影响shared_stuff.a


或者,在极少数情况下,您确实确实需要它在任何地方都具有真正的全局性(例如内置),将其添加到内置模块中。确切的细节在Python 2.x和3.x之间有所不同。在3.x中,它的工作方式如下:

import builtins
import module1
builtins.a = 3
module1.f()

Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static.)

There are different ways to solve this, depending on your actual use case.


Before even going down this path, ask yourself whether this really needs to be global. Maybe you really want a class, with f as an instance method, rather than just a free function? Then you could do something like this:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

If you really do want a global, but it’s just there to be used by module1, set it in that module.

import module1
module1.a=3
module1.f()

On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

… and, in module1.py:

import shared_stuff
def f():
    print shared_stuff.a

Don’t use a from import unless the variable is intended to be a constant. from shared_stuff import a would create a new a variable initialized to whatever shared_stuff.a referred to at the time of the import, and this new a variable would not be affected by assignments to shared_stuff.a.


Or, in the rare case that you really do need it to be truly global everywhere, like a builtin, add it to the builtin module. The exact details differ between Python 2.x and 3.x. In 3.x, it works like this:

import builtins
import module1
builtins.a = 3
module1.f()

回答 1

解决方法是,您可以考虑像这样在外层设置环境变量。

main.py:

import os
os.environ['MYVAL'] = str(myintvariable)

mymodule.py:

import os

myval = None
if 'MYVAL' in os.environ:
    myval = os.environ['MYVAL']

作为额外的预防措施,请在模块内部未定义MYVAL的情况下进行处理。

As a workaround, you could consider setting environment variables in the outer layer, like this.

main.py:

import os
os.environ['MYVAL'] = str(myintvariable)

mymodule.py:

import os

myval = None
if 'MYVAL' in os.environ:
    myval = os.environ['MYVAL']

As an extra precaution, handle the case when MYVAL is not defined inside the module.


回答 2

函数使用其定义模块的全局变量。a = 3例如,应该设置而不是set module1.a = 3。因此,如果要cur用作全局输入utilities_module,请设置utilities_module.cur

更好的解决方案:不要使用全局变量。将所需的变量传递到需要它的函数中,或者创建一个类将所有数据捆绑在一起,并在初始化实例时传递它。

A function uses the globals of the module it’s defined in. Instead of setting a = 3, for example, you should be setting module1.a = 3. So, if you want cur available as a global in utilities_module, set utilities_module.cur.

A better solution: don’t use globals. Pass the variables you need into the functions that need it, or create a class to bundle all the data together, and pass it when initializing the instance.


回答 3

这篇文章只是我遇到的Python行为的观察。如果您做的事情与我在下面做的相同,则上面阅读的建议可能对您不起作用。

即,我有一个包含全局/共享变量的模块(如上所述):

#sharedstuff.py

globaltimes_randomnode=[]
globalist_randomnode=[]

然后,我有一个主要模块,用于导入共享内容:

import sharedstuff as shared

以及实际填充这些数组的其他一些模块。这些由主模块调用。当退出这些其他模块时,我可以清楚地看到已填充了阵列。但是,当在主模块中重新读取它们时,它们为空。这对我来说很奇怪(嗯,我是Python的新手)。但是,当我将主模块中的sharedstuff.py导入方式更改为:

from globals import *

它有效(填充了数组)。

只是在说’

This post is just an observation for Python behaviour I encountered. Maybe the advices you read above don’t work for you if you made the same thing I did below.

Namely, I have a module which contains global/shared variables (as suggested above):

#sharedstuff.py

globaltimes_randomnode=[]
globalist_randomnode=[]

Then I had the main module which imports the shared stuff with:

import sharedstuff as shared

and some other modules that actually populated these arrays. These are called by the main module. When exiting these other modules I can clearly see that the arrays are populated. But when reading them back in the main module, they were empty. This was rather strange for me (well, I am new to Python). However, when I change the way I import the sharedstuff.py in the main module to:

from globals import *

it worked (the arrays were populated).

Just sayin’


回答 4

解决此特定问题的最简单方法是在模块内添加另一个功能,该功能会将光标存储在模块的全局变量中。然后所有其他功能也可以使用它。

模块1:

cursor = None

def setCursor(cur):
    global cursor
    cursor = cur

def method(some, args):
    global cursor
    do_stuff(cursor, some, args)

主程序:

import module1

cursor = get_a_cursor()
module1.setCursor(cursor)
module1.method()

The easiest solution to this particular problem would have been to add another function within the module that would have stored the cursor in a variable global to the module. Then all the other functions could use it as well.

module1:

cursor = None

def setCursor(cur):
    global cursor
    cursor = cur

def method(some, args):
    global cursor
    do_stuff(cursor, some, args)

main program:

import module1

cursor = get_a_cursor()
module1.setCursor(cursor)
module1.method()

回答 5

由于全局变量是特定于模块的,因此可以将以下函数添加到所有导入的模块中,然后将其用于:

  • 将单数变量(以字典格式)添加为这些变量的全局变量
  • 将您的模块全局变量传递给它。

addglobals = lambda x:globals()。update(x)

然后,您需要传递当前的全局变量是:

导入模块

module.addglobals(globals())

Since globals are module specific, you can add the following function to all imported modules, and then use it to:

  • Add singular variables (in dictionary format) as globals for those
  • Transfer your main module globals to it .

addglobals = lambda x: globals().update(x)

Then all you need to pass on current globals is:

import module

module.addglobals(globals())


回答 6

由于我在上面的答案中没有看到它,因此我想我将添加一个简单的解决方法,global_dict即向需要调用模块全局变量的函数添加一个参数,然后在调用时将dict传递给该函数。例如:

# external_module
def imported_function(global_dict=None):
    print(global_dict["a"])


# calling_module
a = 12
from external_module import imported_function
imported_function(global_dict=globals())

>>> 12

Since I haven’t seen it in the answers above, I thought I would add my simple workaround, which is just to add a global_dict argument to the function requiring the calling module’s globals, and then pass the dict into the function when calling; e.g:

# external_module
def imported_function(global_dict=None):
    print(global_dict["a"])


# calling_module
a = 12
from external_module import imported_function
imported_function(global_dict=globals())

>>> 12

回答 7

这样做的OOP方法是使模块成为类,而不是一组未绑定的方法。然后,您可以使用__init__或setter方法来设置来自调用方的变量,以用于模块方法中。

The OOP way of doing this would be to make your module a class instead of a set of unbound methods. Then you could use __init__ or a setter method to set the variables from the caller for use in the module methods.


安装mysqldb python接口时找不到mysql_config

问题:安装mysqldb python接口时找不到mysql_config

我正在尝试使Python脚本在通过ssh连接到的Linux服务器上运行。该脚本使用mysqldb。我有我需要的所有其他组件,但是当我尝试通过setuptools安装mySQLdb时,如下所示:

python setup.py install

我得到以下与mysql_config命令有关的错误报告。

sh: mysql_config: command not found
Traceback (most recent call last):
  File "setup.py", line 15, in <module>
    metadata, options = get_config()
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config
    libs = mysql_config("libs_r")
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config
    raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found

还有其他人遇到此错误吗?如果是,您如何解决该错误/我该怎么做才能成功安装mysqldb?

I am trying to get a Python script to run on the linux server I’m connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:,

python setup.py install

I get the following error report related to the mysql_config command.

sh: mysql_config: command not found
Traceback (most recent call last):
  File "setup.py", line 15, in <module>
    metadata, options = get_config()
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config
    libs = mysql_config("libs_r")
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config
    raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found

Has anyone else encountered this error and if so how did you resolve it/what can I do to successfully install mysqldb?


回答 0

mySQLdb是mysql的python接口,但不是mysql本身。显然,mySQLdb需要命令“ mysql_config”,因此您需要先安装该命令。

您可以通过从shell运行“ mysql”来确认自己是否安装了mysql吗?这应该给您一个响应,而不是“ mysql:not found”。

您使用的是哪个Linux发行版?Mysql已为大多数Linux发行版预先打包。例如,对于debian / ubuntu,安装mysql就像

sudo apt-get install mysql-server

mysql-config位于不同的软件包中,可以从安装(同样,假设debian / ubuntu):

sudo apt-get install libmysqlclient-dev

如果您使用的是mariadb,请替换为mysql,然后运行

sudo apt-get install libmariadbclient-dev

参考:https : //github.com/JudgeGirl/Judge-sender/issues/4#issuecomment-186542797

mySQLdb is a python interface for mysql, but it is not mysql itself. And apparently mySQLdb needs the command ‘mysql_config’, so you need to install that first.

Can you confirm that you did or did not install mysql itself, by running “mysql” from the shell? That should give you a response other than “mysql: command not found”.

Which linux distribution are you using? Mysql is pre-packaged for most linux distributions. For example, for debian / ubuntu, installing mysql is as easy as

sudo apt-get install mysql-server

mysql-config is in a different package, which can be installed from (again, assuming debian / ubuntu):

sudo apt-get install libmysqlclient-dev

if you are using mariadb, the drop in replacement for mysql, then run

sudo apt-get install libmariadbclient-dev

Reference: https://github.com/JudgeGirl/Judge-sender/issues/4#issuecomment-186542797


回答 1

我正在python-mysql使用以下命令在Ubuntu 12.04上安装

pip install mysql-python

首先,我有同样的问题:

Not Found "mysql_config"

这对我有用

$ sudo apt-get install libmysqlclient-dev

然后我有这个问题:

...
_mysql.c:29:20: error fatal: Python.h: No existe el archivo o el directorio

compilación terminada.

error: command 'gcc' failed with exit status 1

然后我尝试了

apt-get install python-dev

然后我很高兴:)

pip install mysql-python
    Installing collected packages: mysql-python
      Running setup.py install for mysql-python
        building '_mysql' extension
        gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'beta',4) -D__version__=1.2.4b4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g
        In file included from _mysql.c:44:0:
        /usr/include/mysql/my_config.h:422:0: aviso: se redefinió "HAVE_WCSCOLL" [activado por defecto]
        /usr/include/python2.7/pyconfig.h:890:0: nota: esta es la ubicación de la definición previa
        gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so

Successfully installed mysql-python
Cleaning up...

I was installing python-mysql on Ubuntu 12.04 using

pip install mysql-python

First I had the same problem:

Not Found "mysql_config"

This worked for me

$ sudo apt-get install libmysqlclient-dev

Then I had this problem:

...
_mysql.c:29:20: error fatal: Python.h: No existe el archivo o el directorio

compilación terminada.

error: command 'gcc' failed with exit status 1

Then I tried with

apt-get install python-dev

And then I was happy :)

pip install mysql-python
    Installing collected packages: mysql-python
      Running setup.py install for mysql-python
        building '_mysql' extension
        gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'beta',4) -D__version__=1.2.4b4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g
        In file included from _mysql.c:44:0:
        /usr/include/mysql/my_config.h:422:0: aviso: se redefinió "HAVE_WCSCOLL" [activado por defecto]
        /usr/include/python2.7/pyconfig.h:890:0: nota: esta es la ubicación de la definición previa
        gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so

Successfully installed mysql-python
Cleaning up...

回答 2

(特定于Mac OS X)

我做了很多尝试,但是这些命令最终对我有用。

  1. 安装 mysql
    brew install mysql
  2. brew unlink mysql
  3. brew install mysql-connector-c
  4. 将mysql bin文件夹添加到PATH
    export PATH=/usr/local/Cellar/mysql/8.0.11/bin:$PATH
  5. mkdir /usr/local/Cellar/lib/
  6. 创建一个符号链接
    sudo ln -s /usr/local/Cellar/mysql/8.0.11/lib/libmysqlclient.21.dylib /usr/local/Cellar/lib/libmysqlclient.21.dylib
  7. brew reinstall openssl来源
  8. 最后,安装mysql-client
    LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/ pip install mysqlclient

更新:如果此方法不起作用,@ vinyll建议brew link mysql在步骤8之前运行。

(Specific to Mac OS X)

I have tried a lot of things, but these set of commands finally worked for me.

  1. Install mysql
    brew install mysql
    
  2. brew unlink mysql
  3. brew install mysql-connector-c
  4. Add the mysql bin folder to PATH
    export PATH=/usr/local/Cellar/mysql/8.0.11/bin:$PATH
    
  5. mkdir /usr/local/Cellar/lib/
  6. Create a symlink
    sudo ln -s /usr/local/Cellar/mysql/8.0.11/lib/libmysqlclient.21.dylib /usr/local/Cellar/lib/libmysqlclient.21.dylib
    
  7. brew reinstall openssl (source)
  8. Finally, install mysql-client
    LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/ pip install mysqlclient
    

Update: In case this doesn’t work, @vinyll suggests to run brew link mysql before step 8.


回答 3

在红帽上,我不得不做

sudo yum install mysql-devel gcc gcc-devel python-devel
sudo easy_install mysql-python

然后它起作用了。

On Red Hat I had to do

sudo yum install mysql-devel gcc gcc-devel python-devel
sudo easy_install mysql-python

Then it worked.


回答 4

以下内容适用于Ubuntu 12.04 LTS:

apt-get install libmysqlclient-dev python-dev

尽管一切正常,但我仍然继续执行以下操作:

export PATH=$PATH:/usr/local/mysql/bin/

The below worked for me on Ubuntu 12.04 LTS:

apt-get install libmysqlclient-dev python-dev

All though it worked, i still went ahead to do the below:

export PATH=$PATH:/usr/local/mysql/bin/

回答 5

尝试安装时出现相同的错误mysql-python

这就是我修复它的方式。

sudo PATH=/usr/local/mysql/bin/:$PATH pip install mysql-python

问题是安装程序无法在默认路径中找到mysql_config。现在它可以..并且有效..

 15 warnings generated.
    clang -bundle -undefined dynamic_lookup -Wl,-F. build/temp.macosx-10.8-intel-2.7/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lz -lm -lmygcc -o build/lib.macosx-10.8-intel-2.7/_mysql.so -arch x86_64

Successfully installed mysql-python
Cleaning up...

希望这可以帮助。

谢谢。

I got the same error while trying to install mysql-python.

This is how I fixed it.

sudo PATH=/usr/local/mysql/bin/:$PATH pip install mysql-python

The problem was that the installer could not find the mysql_config in the default path. Now it can ..and it worked..

 15 warnings generated.
    clang -bundle -undefined dynamic_lookup -Wl,-F. build/temp.macosx-10.8-intel-2.7/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lz -lm -lmygcc -o build/lib.macosx-10.8-intel-2.7/_mysql.so -arch x86_64

Successfully installed mysql-python
Cleaning up...

Hope this helps.

Thanks.


回答 6

我通过以下步骤解决了此问题:

sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev
sudo python setup.py install

I fixed this problem with the following steps:

sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev
sudo python setup.py install

回答 7

命令(也是mysql)mPATH可能丢失。

export PATH=$PATH:/usr/local/mysql/bin/

The commands (mysql too) mPATH might be missing.

export PATH=$PATH:/usr/local/mysql/bin/


回答 8

步骤1:-同时安装Python3和Python3-dev

sudo apt-get install python3 python3-dev

步骤2:- 安装Python和Mysql连接器

sudo apt-get install libmysqlclient-dev

步骤3:- 安装python mysql客户端

sudo apt-get install mysqlclient

这将解决您的问题

Step1:-Install Python3 & Python3-dev Both

sudo apt-get install python3 python3-dev

Step2:- Install Python & Mysql Connector

sudo apt-get install libmysqlclient-dev

step3:- Install python mysql client

sudo apt-get install mysqlclient

This will Solve your Problem


回答 9

如果您使用的是macOS,并且已经通过brew install安装了mysql@5.7,请执行以下操作:

  1. brew install mysql-connector-c
  2. brew unlink mysql@5.7
  3. brew link --overwrite --dry-run mysql@5.7 首先,查看哪些符号链接被覆盖
  4. brew link --overwrite --force mysql@5.7 用mysql@5.7实际覆盖与mysql相关的符号链接
  5. pip install mysqlclient

If you’re on macOS and already installed mysql@5.7 via brew install:

  1. brew install mysql-connector-c
  2. brew unlink mysql@5.7
  3. brew link --overwrite --dry-run mysql@5.7 first, to see what symlinks are getting overwritten
  4. brew link --overwrite --force mysql@5.7 to actually overwrite mysql-related symlinks with mysql@5.7
  5. pip install mysqlclient

回答 10

我通过安装libmysqlclient来修复它:

sudo apt-get install libmysqlclient16-dev

I fixed it by installing libmysqlclient:

sudo apt-get install libmysqlclient16-dev

回答 11

MySQL-python软件包正在使用该mysql_config命令来了解mysql主机上的配置。您的主机没有该mysql_config命令。

来自dev.mysql.com的MySQL开发库程序包(MySQL-devel-xxx)提供了此命令以及MySQL-python程序包所需的库。MySQL-devel可在下载-社区服务器区域中找到这些软件包。MySQL开发库软件包名称MySQL-devel以MySQL版本和linux平台(例如MySQL-devel-5.5.24-1.linux2.6.x86_64.rpm)为基础,并有所不同。

注意,您不需要安装mysql服务器。

The MySQL-python package is using the mysql_config command to learn about the mysql configuration on your host. Your host does not have the mysql_config command.

The MySQL development libraries package (MySQL-devel-xxx) from dev.mysql.com provides this command and the libraries needed by the MySQL-python package. The MySQL-devel packages are found in the download – community server area. The MySQL development library package names start with MySQL-devel and vary based MySQL version and linux platform (e.g. MySQL-devel-5.5.24-1.linux2.6.x86_64.rpm.)

Note that you do not need to install mysql server.


回答 12

不建议使用libmysqlclient-dev软件包,因此请使用以下命令对其进行修复。

软件包libmysqlclient-dev不可用,但是由另一个软件包引用。这可能意味着该软件包已丢失,已被废弃或只能从其他来源获得

sudo apt-get install default-libmysqlclient-dev

The package libmysqlclient-dev is deprecated, so use the below command to fix it.

Package libmysqlclient-dev is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source

sudo apt-get install default-libmysqlclient-dev

回答 13

在centos 7中,这对我有用:

yum install mariadb-devel
pip install mysqlclient

In centos 7 this works for me :

yum install mariadb-devel
pip install mysqlclient

回答 14

在我的Fedora 23机器上,我必须运行以下命令:

sudo dnf install mysql-devel

On my Fedora 23 machine I had to run the following:

sudo dnf install mysql-devel

回答 15

对于Alpine Linux:

$ apk add mariadb-dev mariadb-client mariadb-libs

MariaDB是MySQL的直接替代品,并成为Alpine 3.2的新标准。参见https://bugs.alpinelinux.org/issues/4264

For Alpine Linux:

$ apk add mariadb-dev mariadb-client mariadb-libs

MariaDB is a drop-in replacement for MySQL and became the new standard as of Alpine 3.2. See https://bugs.alpinelinux.org/issues/4264


回答 16

我认为,以下几行可以在终端上执行

 sudo ln -s /usr/local/zend/mysql/bin/mysql_config /usr/sbin/

该mysql_config目录用于MacOSx上的zend服务器。您可以像下面的几行一样在linux上做

sudo ln -s /usr/local/mysql/bin/mysql_config /usr/sbin/

这是默认的Linux mysql目录。

I think, following lines can be executed on terminal

 sudo ln -s /usr/local/zend/mysql/bin/mysql_config /usr/sbin/

This mysql_config directory is for zend server on MacOSx. You can do it for linux like following lines

sudo ln -s /usr/local/mysql/bin/mysql_config /usr/sbin/

This is default linux mysql directory.


回答 17

我遇到了这个问题,并通过将符号链接添加到来解决mysql_config

我已经用自制软件安装了mysql,并在输出中看到了这一点。

Error: The `brew link` step did not complete successfully

根据您的购买方式,mysql它会出现在不同的地方。以我为例,/usr/local/Cellar/mysql
一旦您知道它在哪里,就应该可以建立一个指向python寻找位置的符号链接。 /usr/local/mysql

这对我有用。

ln -s /usr/local/Cellar/mysql/<< VERSION >>/bin/mysql_config   /usr/local/mysql/bin/mysql_config

I had this issues and solved if by adding a symlink to mysql_config.

I had installed mysql with homebrew and saw this in the output.

Error: The `brew link` step did not complete successfully

Depending on how you got mysql it will be in different places. In my case /usr/local/Cellar/mysql
Once you know where it is you should be able to ma a symbolic link to where python is looking for it. /usr/local/mysql

This worked for me.

ln -s /usr/local/Cellar/mysql/<< VERSION >>/bin/mysql_config   /usr/local/mysql/bin/mysql_config

回答 18

我有同样的问题。我通过按照本教程在Ubuntu 16.04上使用python3-dev安装Python的方式解决了问题:

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get install -y python3-pip
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev

现在您可以设置虚拟环境:

sudo apt-get install -y python3-venv
pyvenv my_env
source my_env/bin/activate

I had the same problem. I solved it by following this tutorial to install Python with python3-dev on Ubuntu 16.04:

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get install -y python3-pip
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev

And now you can set up your virtual environment:

sudo apt-get install -y python3-venv
pyvenv my_env
source my_env/bin/activate

回答 19

您需要安装python-dev软件包:

sudo apt-get install python-dev

You need to install the python-dev package:

sudo apt-get install python-dev

回答 20

须藤apt-get install python-mysqldb

Python 2.5?听起来您正在使用非常旧的Ubuntu Server版本(Hardy 8.04?)-请确认服务器使用的Linux版本。

在ubuntu软件包数据库上搜索python-mysql

一些其他信息:

从mysql-python的自述文件-

红帽Linux ………….

MySQL-python已预包装在Red Hat Linux 7.x和更高版本中。这包括Fedora Core和Red Hat Enterprise Linux。您还可以如上所述构建自己的RPM软件包。

Debian GNU / Linux …………….

打包为python-mysqldb_ ::

# apt-get install python-mysqldb

或使用Synaptic。

.. _ python-mysqldbhttp : //packages.debian.org/python-mysqldb

Ubuntu ……

与Debian相同。

脚注:如果您确实使用的服务器发行版早于Ubuntu 10.04,则您不受官方支持,因此应尽快升级。

sudo apt-get install python-mysqldb

Python 2.5? Sounds like you are using a very old version of Ubuntu Server (Hardy 8.04?) – please confirm which Linux version the server uses.

python-mysql search on ubuntu package database

Some additional info:

From the README of mysql-python –

Red Hat Linux ………….

MySQL-python is pre-packaged in Red Hat Linux 7.x and newer. This includes Fedora Core and Red Hat Enterprise Linux. You can also build your own RPM packages as described above.

Debian GNU/Linux …………….

Packaged as python-mysqldb_::

# apt-get install python-mysqldb

Or use Synaptic.

.. _python-mysqldb: http://packages.debian.org/python-mysqldb

Ubuntu ……

Same as with Debian.

Footnote: If you really are using a server distribution older than Ubuntu 10.04 then you are out of official support, and should upgrade sooner rather than later.


回答 21

该方法仅适用于那些知道已安装Mysql但仍找不到mysql_config的用户。如果python安装无法在系统路径中找到mysql_config,则会发生这种情况,如果通过.dmg Mac Package完成安装或在某个自定义路径中进行安装,则通常会发生这种情况。MySqlDB最简单且记录在案的方法是更改site.cfg。找到可能位于/ usr / local / mysql / bin /中的mysql_config,然后像下面那样更改变量mysql_config,然后再次运行安装。不要忘记通过删除“#”取消注释

在行下更改

“ #mysql_config = / usr / local / bin / mysql_config”

“ mysql_config = / usr / local / mysql / bin / mysql_config”

取决于系统中的路径。

顺便说一句,我在更改site.cfg之后使用python安装

sudo /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python setup.py安装

This method is only for those who know that Mysql is installed but still mysql_config can’t be find. This happens if python install can’t find mysql_config in your system path, which mostly happens if you have done the installation via .dmg Mac Package or installed at some custom path. The easiest and documented way by MySqlDB is to change the site.cfg. Find the mysql_config which is probably in /usr/local/mysql/bin/ and change the variable namely mysql_config just like below and run the installation again. Don’t forget to un-comment it by removing “#”

Change below line

“#mysql_config = /usr/local/bin/mysql_config”

to

“mysql_config = /usr/local/mysql/bin/mysql_config”

depending upon the path in your system.

By the way I used python install after changing the site.cfg

sudo /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python setup.py install


回答 22

到目前为止,所有解决方案(Linux)都需要具有sudoroot用户权限才能安装。如果您没有root权限且没有root权限,则这是一个解决方案sudo。(否sudo apt install ...):

  1. 从此镜像下载libmysqlclient-dev的.deb文件
  2. 导航到下载的文件并运行。dpkg -x libmysqlclient-dev_<version tag>.deb .这将提取一个名为的文件夹usr
  3. 符号链接./usr/bin/mysql_config到您的上找到的某个位置$PATH

    ln -s `pwd` /usr/bin/mysql_config FOLDER_IN_YOUR_PATH

  4. 现在应该可以找到 mysql_config

在Ubuntu 18.04上测试。

So far, all solutions (Linux) require sudo or root rights to install . Here is a solution if you do not have root rights and without sudo. (no sudo apt install ...):

  1. Download the .deb file of the libmysqlclient-dev, e.g. from this mirror
  2. Navigate to the downloaded file and run dpkg -x libmysqlclient-dev_<version tag>.deb . This will extract a folder called usr.
  3. Symlink ./usr/bin/mysql_config to somewhere that is found on your $PATH:

    ln -s `pwd` /usr/bin/mysql_config FOLDER_IN_YOUR_PATH

  4. It should now be able to find mysql_config

Tested on Ubuntu 18.04.


回答 23

对于macOS Mojave,需要附加配置,编译器才能找到openssl,您可能需要设置:

export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

For macOS Mojave , additional configuration was required, for compilers to find openssl you may need to set:

export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

回答 24

我认为在2020年解决此问题的最便捷方法是使用另一个python软件包。我们不需要安装任何其他二进制软件。

尝试这个

pip install mysql-connector-python

然后

import mysql.connector

mydb = mysql.connector.connect(
          host="",
          user="",
          passwd="",
          database=""
          )      
cursor = mydb.cursor( buffered=True)
cursor.execute('show tables;')
cursor.execute('insert into test values (null, "a",10)')
mydb.commit()
mydb.disconnect()

I think the most convenient way to solve this problem in 2020 is using another python package. We don’t need install any other binary software.

Try this

pip install mysql-connector-python

and then

import mysql.connector

mydb = mysql.connector.connect(
          host="",
          user="",
          passwd="",
          database=""
          )      
cursor = mydb.cursor( buffered=True)
cursor.execute('show tables;')
cursor.execute('insert into test values (null, "a",10)')
mydb.commit()
mydb.disconnect()

回答 25

我遇到了同样的问题,只是将* mysql_config *所在的路径添加到环境变量PATH中,它对我有用。

I encountered the same problem, just added the path where *mysql_config* resided to the environment variable PATH and it worked for me.


回答 26

sudo apt-get build-dep python-mysqldb 将安装所有依赖项以从PIP / easy_install构建软件包

sudo apt-get build-dep python-mysqldb will install all the dependencies to build the package from PIP/easy_install


回答 27

由于实际错误是

gcc ... -I/usr/include/python2.7 ...

_mysql.c:29:20: error: Python.h: No such file or directory

并且如果您无法安装python-dev或python-devel软件包,则可以从http://hg.python.org/下载包含所需版本的python源的存档,并将标头文件放置在正确的文件夹中,以包含

As actual error is

gcc ... -I/usr/include/python2.7 ...

_mysql.c:29:20: error: Python.h: No such file or directory

and If you can’t install python-dev or python-devel packages, you may download archive with needed version of python sources from http://hg.python.org/ and place headers files in proper folder for include


回答 28

只需输入:

$ sudo apt-get install python-dev
$ venv/bin/pip install MySQL-python

这样可以解决这个问题。

Just type:

$ sudo apt-get install python-dev
$ venv/bin/pip install MySQL-python

This will solve this problems.


回答 29

在CentOS 7中,应执行以下操作:

#step1:install mysql 
https://dev.mysql.com/doc/mysql-yum-repo-quick-guide/en/

#step2:
sudo yum install mysql-devel

In CentOS 7 , the following things should be done:

#step1:install mysql 
https://dev.mysql.com/doc/mysql-yum-repo-quick-guide/en/

#step2:
sudo yum install mysql-devel

pip安装mysql-python失败,并显示EnvironmentError:找不到mysql_config

问题:pip安装mysql-python失败,并显示EnvironmentError:找不到mysql_config

这是我得到的错误

(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
  Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
  Running setup.py egg_info for package mysql-python
    sh: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 14, in <module>
      File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 24, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    Complete output from command python setup.py egg_info:
    sh: mysql_config: not found

Traceback (most recent call last):

  File "<string>", line 14, in <module>

  File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>

    metadata, options = get_config()

  File "setup_posix.py", line 43, in get_config

    libs = mysql_config("libs_r")

  File "setup_posix.py", line 24, in mysql_config

    raise EnvironmentError("%s not found" % (mysql_config.path,))

EnvironmentError: mysql_config not found

----------------------------------------
Command python setup.py egg_info failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
  Running setup.py egg_info for package mysql-python
    sh: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 14, in <module>
      File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 24, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    Complete output from command python setup.py egg_info:
    sh: mysql_config: not found

Traceback (most recent call last):

  File "<string>", line 14, in <module>

  File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>

    metadata, options = get_config()

  File "setup_posix.py", line 43, in get_config

    libs = mysql_config("libs_r")

  File "setup_posix.py", line 24, in mysql_config

    raise EnvironmentError("%s not found" % (mysql_config.path,))

EnvironmentError: mysql_config not found

----------------------------------------
Command python setup.py egg_info failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log

我该怎么解决?

This is the error I get

(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
  Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
  Running setup.py egg_info for package mysql-python
    sh: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 14, in <module>
      File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 24, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    Complete output from command python setup.py egg_info:
    sh: mysql_config: not found

Traceback (most recent call last):

  File "<string>", line 14, in <module>

  File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>

    metadata, options = get_config()

  File "setup_posix.py", line 43, in get_config

    libs = mysql_config("libs_r")

  File "setup_posix.py", line 24, in mysql_config

    raise EnvironmentError("%s not found" % (mysql_config.path,))

EnvironmentError: mysql_config not found

----------------------------------------
Command python setup.py egg_info failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
  Running setup.py egg_info for package mysql-python
    sh: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 14, in <module>
      File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 24, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    Complete output from command python setup.py egg_info:
    sh: mysql_config: not found

Traceback (most recent call last):

  File "<string>", line 14, in <module>

  File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>

    metadata, options = get_config()

  File "setup_posix.py", line 43, in get_config

    libs = mysql_config("libs_r")

  File "setup_posix.py", line 24, in mysql_config

    raise EnvironmentError("%s not found" % (mysql_config.path,))

EnvironmentError: mysql_config not found

----------------------------------------
Command python setup.py egg_info failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log

What can I do to resolve this?


回答 0

看来您的系统上缺少mysql_config或安装程序找不到它。确保确实安装了mysql_config。

例如,在Debian / Ubuntu上,您必须安装软件包:

sudo apt-get install libmysqlclient-dev

也许mysql_config不在您的路径中,当您自己编译mysql套件时就是这种情况。

更新:对于最新版本的debian / ubuntu(截至2018年),它是

sudo apt install default-libmysqlclient-dev

It seems mysql_config is missing on your system or the installer could not find it. Be sure mysql_config is really installed.

For example on Debian/Ubuntu you must install the package:

sudo apt-get install libmysqlclient-dev

Maybe the mysql_config is not in your path, it will be the case when you compile by yourself the mysql suite.

Update: For recent versions of debian/ubuntu (as of 2018) it is

sudo apt install default-libmysqlclient-dev

回答 1

在Mac OS中,我只是在终端中运行此程序来修复:

export PATH=$PATH:/usr/local/mysql/bin

这是我找到的最快的修复程序-将其添加到路径中,但是/etc/paths如果您打算在其他环境中安装MySQL-python,最好永久添加(即将其添加到)。

(在OSX Mountain Lion中测试)

In Mac OS, I simply ran this in terminal to fix:

export PATH=$PATH:/usr/local/mysql/bin

This is the quickest fix I found – it adds it to the path, but I think you’re better off adding it permanently (ie add it to /etc/paths) if you plan to install MySQL-python in another environment.

(tested in OSX Mountain Lion)


回答 2

apt-get install libmysqlclient-dev python-dev

似乎做到了。

apt-get install libmysqlclient-dev python-dev

Seemed to do the trick.


回答 3

上面的问题可能有各种答案,下面是一个汇总的解决方案。

对于Ubuntu:

$ sudo apt update
$ sudo apt install python-dev
$ sudo apt install python-MySQLdb

对于CentOS:

$ yum install python-devel mysql-devel

There maybe various answers for the above issue, below is a aggregated solution.

For Ubuntu:

$ sudo apt update
$ sudo apt install python-dev
$ sudo apt install python-MySQLdb

For CentOS:

$ yum install python-devel mysql-devel

回答 4

如果您使用的是MAC,请全局安装

brew install mysql

然后像这样导出路径

export PATH=$PATH:/usr/local/mysql/bin

比全球或您喜欢的任何方式

pip install MySQL-Python

注意:全局适用于python3,因为Mac可以同时拥有python2和3

pip3 install MySQL-Python

If you are on MAC Install this globally

brew install mysql

then export path like this

export PATH=$PATH:/usr/local/mysql/bin

Than globally or in your venv whatever you like

pip install MySQL-Python

Note: globally for python3 as Mac can have both python2 & 3

pip3 install MySQL-Python

回答 5

您可以使用MySQL Connector / Python

通过PyPip安装

pip install mysql-connector-python

可以在MySQL Connector / Python 1.0.5 beta公告博客上找到更多信息。

在Launchpad上,有一个很好的示例,说明如何使用该库添加,编辑或删除数据

You can use the MySQL Connector/Python

Installation via PyPip

pip install mysql-connector-python

Further information can be found on the MySQL Connector/Python 1.0.5 beta announcement blog.

On Launchpad there’s a good example of how to add-, edit- or remove data with the library.


回答 6

对于centos用户:

yum install -y mysql-devel python-devel python-setuptools

然后

pip install MySQL-python


如果此解决方案不起作用,请打印gcc编译错误,例如:
_mysql.c:29:20: error: Python.h: No such file or directory

您需要指定的路径Python.h,如下所示:
pip install --global-option=build_ext --global-option="-I/usr/include/python2.6" MySQL-python

For centos users:

yum install -y mysql-devel python-devel python-setuptools

then

pip install MySQL-python


If this solution doesn’t work, and print gcc compile error like:
_mysql.c:29:20: error: Python.h: No such file or directory

You need to specify the path of Python.h, like this:
pip install --global-option=build_ext --global-option="-I/usr/include/python2.6" MySQL-python


回答 7

我试图mysql-python在Amazon EC2 Linux实例上安装,但我必须安装这些:

yum install mysql mysql-devel mysql-common mysql-libs gcc

但是后来我得到了这个错误:

_mysql.c:29:20: fatal error: Python.h: No such file or directory

所以我安装了:

yum install python-devel

那就成功了。

I was trying to install mysql-python on an Amazon EC2 Linux instance and I had to install these :

yum install mysql mysql-devel mysql-common mysql-libs gcc

But then I got this error :

_mysql.c:29:20: fatal error: Python.h: No such file or directory

So I installed :

yum install python-devel

And that did the trick.


回答 8

对于任何使用MariaDB而不是MySQL的用户,解决方案是安装libmariadbclient-dev软件包并创建指向具有正确名称的配置文件的符号链接。

例如,这对我有用:

ln -s /usr/bin/mariadb_config /usr/bin/mysql_config

For anyone that is using MariaDB instead of MySQL, the solution is to install the libmariadbclient-dev package and create a symbolic link to the config file with the correct name.

For example this worked for me:

ln -s /usr/bin/mariadb_config /usr/bin/mysql_config

回答 9

尝试 sudo apt-get build-dep python-mysqldb

Try sudo apt-get build-dep python-mysqldb


回答 10

OSX小牛

由于osx mavericks和xcode开发工具中的更改,您可能会在安装时得到错误

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]

因此使用:

sudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install mysql-python

OSX Mavericks

Due to changes within osx mavericks & xcode development tools you may get the error on installation

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]

therefore use :

sudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install mysql-python

回答 11

对于Linux

这对我有用

yum install python-devel mysql-devel

For Linux

this works for me

yum install python-devel mysql-devel

回答 12

对于mariadb,请安装lib mariadb client-dev而不是libmysqlclient-dev

sudo apt-get install libmariadbclient-dev

for mariadb install libmariadbclient-dev instead of libmysqlclient-dev

sudo apt-get install libmariadbclient-dev

回答 13

您应该安装第mysql一个:

yum install python-devel mysql-community-devel -y

然后您可以安装mysqlclient

pip install  mysqlclient

You should install the mysql first:

yum install python-devel mysql-community-devel -y

Then you can install mysqlclient:

pip install  mysqlclient

回答 14

有时,错误取决于实际原因。我们曾经遇到过通过python-mysqldb debian软件包安装mysql-python的情况。

一个不知道这一点的开发人员,无意中跑了出来,但pip uninstall mysql-python由于pip install mysql-python给出上述错误而无法恢复。

pip uninstall mysql-python已经破坏了debian软件包的内容,当然pip install mysql-python失败了,因为debian软件包不需要任何dev文件。

在这种情况下,正确的解决方案是apt-get install --reinstall python-mysqldb将mysql-python恢复到其原始状态。

sometimes the error depends on the actual cause. we had a case where mysql-python was installed through the python-mysqldb debian package.

a developer who didn’t know this, accidentally ran pip uninstall mysql-python and then failed to recover with pip install mysql-python giving the above error.

pip uninstall mysql-python had destroyed the debian package contents, and of course pip install mysql-python failed because the debian package didn’t need any dev files.

the correct solution in that case was apt-get install --reinstall python-mysqldb which restored mysql-python to its original state.


回答 15

我在Terraform:light容器中遇到了同样的问题。它基于高山。

在那里,您必须使用以下命令安装mariadb-dev:

apk add mariadb-dev

但是,这还不够,因为还遗漏了所有其他依赖项:

apk add python2 py2-pip gcc python2-dev musl-dev

I had the same problem in the Terraform:light container. It is based on Alpine.

There you have to install mariadb-dev with:

apk add mariadb-dev

But that one is not enough because also all the other dependencies are missed:

apk add python2 py2-pip gcc python2-dev musl-dev

回答 16

要遵循的顺序。

pip install mysqlclient
sudo apt-get install python3-dev libmysqlclient-dev
pip install configparser 
sudo cp /usr/lib/python3.6/configparser.py /usr/lib/python3.6/ConfigParser.py 

然后尝试再次安装MYSQL-python。对我有用

Sequence to be followed.

pip install mysqlclient
sudo apt-get install python3-dev libmysqlclient-dev
pip install configparser 
sudo cp /usr/lib/python3.6/configparser.py /usr/lib/python3.6/ConfigParser.py 

Then try to install the MYSQL-python again. That Worked for me


回答 17

尝试在OS X Server 10.6.8上安装时遇到了类似的问题。这就是我要做的。使用:

MySQL-python 1.2.4b4(源)MySQL-5.6.19(二进制安装程序)Python 2.7(二进制安装程序)注意:在virtualenv中安装…

解压缩源代码,打开’distribute_setup.py’并编辑DEFAULT_VERSION以使用最新版本的分发工具,如下所示:

DEFAULT_VERSION = "0.6.49"

救。打开“ site.cfg”文件,取消注释mysql_config的路径,使其看起来像(参考您自己的mysql_config路径):

# The path to mysql_config.
# Only use this if mysql_config is not on your PATH, or you have some weird
# setup that requires it.
mysql_config = /usr/local/mysql/bin/mysql_config

现在,清理,构建和制作不会因找不到“ mysql_config”错误而失败。希望这可以帮助其他尝试利用其旧xserve的人:-)

Had a similar issue trying to install on OS X Server 10.6.8. Here’s what I had to do. Using:

MySQL-python 1.2.4b4 (source) MySQL-5.6.19 (binary installer) Python 2.7 (binary installer) NOTE: Installing in virtualenv…

Unzip source, open ‘distribute_setup.py’ and edit DEFAULT_VERSION to use the latest version of distribute tools, like so:

DEFAULT_VERSION = "0.6.49"

Save. Open ‘site.cfg’ file and uncomment the path to mysql_config so it looks something like (reference your own path to mysql_config):

# The path to mysql_config.
# Only use this if mysql_config is not on your PATH, or you have some weird
# setup that requires it.
mysql_config = /usr/local/mysql/bin/mysql_config

Now clean, build and make will not fail with the ‘mysql_config’ not found error. Hope this helps someone else trying to make use of their old xserves :-)


回答 18

您的sudo路径不知道您的本地路径…进入超级用户模式,添加路径,然后从那里安装它。

sudo su
export PATH=$PATH:/usr/local/mysql/bin/
pip install mysql-python
exit

您就可以在OSX上运行了。现在,您有了一个更新的全局python。

Your sudo path does not know about your local path… go into superuser mode, add the path, and install it from there.

sudo su
export PATH=$PATH:/usr/local/mysql/bin/
pip install mysql-python
exit

And you’re up and running on OSX. Now you have an updated global python.


回答 19

如果在虚拟环境中安装MySQL-python,则应检查pip版本,如果该版本早于9.0.1,请进行更新

pip install --upgrade pip

if you install MySQL-python in your virtual env, you should check the pip version, if the version is older than 9.0.1, please update it

pip install --upgrade pip

回答 20

在MacOS Mojave上,mysql_config位于/ usr / local / bin /而不是如上所述的/ usr / local / mysql / bin,因此无需在路径中添加任何内容。

on MacOS Mojave, mysql_config is found at /usr/local/bin/ rather than /usr/local/mysql/bin as pointed above, so no need to add anything to path.


使用pip安装特定的软件包版本

问题:使用pip安装特定的软件包版本

我正在尝试使用通过该--no-site-packages选项创建的新virtualenv安装MySQL_python适配器的1.2.2版本。PyPi中显示的当前版本是1.2.3。有没有办法安装旧版本?我发现有一篇文章指出应该这样做:

pip install MySQL_python==1.2.2

但是,安装后,它仍显示MySQL_python-1.2.3-py2.6.egg-info在站点包中。这是此软件包专用的问题,还是我做错了什么?

I’m trying to install version 1.2.2 of the MySQL_python adaptor, using a fresh virtualenv created with the --no-site-packages option. The current version shown in PyPi is 1.2.3. Is there a way to install the older version? I found an article stating that this should do it:

pip install MySQL_python==1.2.2

When installed, however, it still shows MySQL_python-1.2.3-py2.6.egg-info in the site packages. Is this a problem specific to this package, or am I doing something wrong?


回答 0

TL; DR:

  • pip install -Iv(即pip install -Iv MySQL_python==1.2.2

首先,我发现您要执行的操作有两个问题。由于您已经安装了版本,因此应该卸载当前的现有驱动程序或使用pip install -I MySQL_python==1.2.2

但是,您很快就会发现这不起作用。如果您查看pip的安装日志,或者执行pip的安装日志,pip install -Iv MySQL_python==1.2.2则会发现PyPI URL链接不适用于MySQL_python v1.2.2。您可以在这里验证:http : //pypi.python.org/pypi/MySQL-python/1.2.2

由于sourceforge.net的最新升级和PyPI的过时URL,下载链接404s和后备URL链接正在无限重定向。

因此,要正确安装驱动程序,可以按照以下步骤操作:

pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download

TL;DR:

  • pip install -Iv (i.e. pip install -Iv MySQL_python==1.2.2)

First, I see two issues with what you’re trying to do. Since you already have an installed version, you should either uninstall the current existing driver or use pip install -I MySQL_python==1.2.2

However, you’ll soon find out that this doesn’t work. If you look at pip’s installation log, or if you do a pip install -Iv MySQL_python==1.2.2 you’ll find that the PyPI URL link does not work for MySQL_python v1.2.2. You can verify this here: http://pypi.python.org/pypi/MySQL-python/1.2.2

The download link 404s and the fallback URL links are re-directing infinitely due to sourceforge.net’s recent upgrade and PyPI’s stale URL.

So to properly install the driver, you can follow these steps:

pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download

回答 1

您甚至可以在pip install命令中使用版本范围。像这样:

pip install 'stevedore>=1.3.0,<1.4.0'

如果该软件包已经安装,并且您想降级,请添加--force-reinstall以下内容:

pip install 'stevedore>=1.3.0,<1.4.0' --force-reinstall

You can even use a version range with pip install command. Something like this:

pip install 'stevedore>=1.3.0,<1.4.0'

And if the package is already installed and you want to downgrade it add --force-reinstall like this:

pip install 'stevedore>=1.3.0,<1.4.0' --force-reinstall

回答 2

一种方法,在提出这个职位,是提版本pip为:

pip install -Iv MySQL_python==1.2.2

即使用==并提及版本号以仅安装该版本。-I, --ignore-installed忽略已经安装的软件包。

One way, as suggested in this post, is to mention version in pip as:

pip install -Iv MySQL_python==1.2.2

i.e. Use == and mention the version number to install only that version. -I, --ignore-installed ignores already installed packages.


回答 3

要安装特定的python软件包版本,无论是第一次,升级还是降级,请使用:

pip install --force-reinstall MySQL_python==1.2.4

MySQL_python版本1.2.2不可用,因此我使用了其他版本。要从索引查看所有可用的软件包版本,请排除该版本:

pip install MySQL_python==

To install a specific python package version whether it is the first time, an upgrade or a downgrade use:

pip install --force-reinstall MySQL_python==1.2.4

MySQL_python version 1.2.2 is not available so I used a different version. To view all available package versions from an index exclude the version:

pip install MySQL_python==

回答 4

我相信,如果您已经安装了软件包,pip不会用其他版本覆盖它。使用-I忽略以前的版本。

I believe that if you already have a package it installed, pip will not overwrite it with another version. Use -I to ignore previous versions.


回答 5

有时,先前安装的版本会被缓存。

~$ pip install pillow==5.2.0

它返回以下内容:
已满足要求:/home/ubuntu/anaconda3/lib/python3.6/site-packages(5.2.0)中的pillow == 5.2.0

我们可以将–no-cache-dir与-I一起使用来覆盖它

~$ pip install --no-cache-dir -I pillow==5.2.0

Sometimes, the previously installed version is cached.

~$ pip install pillow==5.2.0

It returns the followings:
Requirement already satisfied: pillow==5.2.0 in /home/ubuntu/anaconda3/lib/python3.6/site-packages (5.2.0)

We can use –no-cache-dir together with -I to overwrite this

~$ pip install --no-cache-dir -I pillow==5.2.0

回答 6

由于这似乎是pip版本10中引入的重大更改,因此我降级为兼容版本:

pip install 'pip<10' 

该命令告诉pip安装低于版本10的模块版本。在virutalenv中执行此操作,这样就不会增加Python站点安装的麻烦

Since this appeared to be a breaking change introduced in version 10 of pip, I downgraded to a compatible version:

pip install 'pip<10' 

This command tells pip to install a version of the module lower than version 10. Do this in a virutalenv so you don’t screw up your site installation of Python.


回答 7

我最近在使用想要记录到某处pip-I标志时遇到问题:

-I卸载继续之前的现有的包; 它将仅安装在旧版本的顶部。这意味着应将两个版本之间应删除的所有文件保留在原处。如果这些文件与其他已安装模块共享名称,则可能导致奇怪的行为。

例如,假设有一个名为的软件包package。在的一个package文件中,他们使用import datetime。现在,在中package@2.0.0,它指向标准库datetime模块,但是在中package@3.0.0,他们添加了本地语言datetime.py以替代标准库版本(无论出于何种原因)。

现在说我跑步pip install package==3.0.0,但后来意识到我实际上想要版本2.0.0。如果我现在运行pip install -I package==2.0.0datetime.py文件将不会被删除,因此任何调用import datetime都会导入错误的模块。

就我而言,这表现为奇怪的语法错误,因为该软件包的较新版本添加了仅与Python 3兼容的文件,并且当我将软件包版本降级以支持Python 2时,我继续导入仅Python-3模块。

基于此,我认为-I在更新已安装的软件包版本时,总是比使用旧软件包更可取。

I recently ran into an issue when using pip‘s -I flag that I wanted to document somewhere:

-I will not uninstall the existing package before proceeding; it will just install it on top of the old one. This means that any files that should be deleted between versions will instead be left in place. This can cause weird behavior if those files share names with other installed modules.

For example, let’s say there’s a package named package. In one of packages files, they use import datetime. Now, in package@2.0.0, this points to the standard library datetime module, but in package@3.0.0, they added a local datetime.py as a replacement for the standard library version (for whatever reason).

Now lets say I run pip install package==3.0.0, but then later realize that I actually wanted version 2.0.0. If I now run pip install -I package==2.0.0, the old datetime.py file will not be removed, so any calls to import datetime will import the wrong module.

In my case, this manifested with strange syntax errors because the newer version of the package added a file that was only compatible with Python 3, and when I downgraded package versions to support Python 2, I continued importing the Python-3-only module.

Based on this, I would argue that uninstalling the old package is always preferable to using -I when updating installed package versions.


回答 8

下面的命令对我有用

Python版本-2.7

包-python-jenkins

命令- $ pip install 'python-jenkins>=1.1.1'

This below command worked for me

Python version – 2.7

package – python-jenkins

command – $ pip install 'python-jenkins>=1.1.1'


回答 9

您可以通过两种方式安装任何版本的软件包: -A)。pip install -Iv软件包名称==版本 B)。pip install -v软件包名称==版本

为一个

在这里,如果您在安装时使用-I选项(当您不知道该软件包是否已安装时)(例如’pip install -Iv pyreadline == 2. *’之类的东西),则您将在安装新的单独的程序包,而相同的现有程序包具有不同的版本。

对于B

  1. 首先,您可能要检查是否有违反要求的情况。 点子检查

2.然后查看点子列表已经安装了什么

3.如果软件包列表中包含您要安装的特定版本的软件包,那么更好的选择是先通过pip uninstall package-name卸载该版本的软件包。

4.现在,您可以继续通过pip install -v package-name == version重新安装具有特定版本的相同软件包, 例如pip install -v pyreadline == 2. *

There are 2 ways you may install any package with version:- A). pip install -Iv package-name == version B). pip install -v package-name == version

For A

Here, if you’re using -I option while installing(when you don’t know if the package is already installed) (like ‘pip install -Iv pyreadline == 2.* ‘or something), you would be installing a new separate package with the same existing package having some different version.

For B

  1. At first, you may want to check for no broken requirements. pip check

2.and then see what’s already installed by pip list

3.if the list of the packages contain any package that you wish to install with specific version then the better option is to uninstall the package of this version first, by pip uninstall package-name

4.And now you can go ahead to reinstall the same package with a specific version, by pip install -v package-name==version e.g. pip install -v pyreadline == 2.*


回答 10

如果要更新为最新版本,但您不知道可以输入的是最新版本。

pip安装MySQL_python –upgrade

这将更新可用的最新版本的MySQL_python,您可以将其用于任何其他软件包版本。

If you want to update to latest version and you don’t know what is the latest version you can type.

pip install MySQL_python –upgrade

This will update the MySQL_python for latest version available, you can use for any other package version.