标签归档:debian

设置Django以使用MySQL

问题:设置Django以使用MySQL

我想稍微远离PHP,学习Python。为了使用Python进行Web开发,我需要一个框架来帮助模板和其他事情。

我有一台非生产服务器,用于测试所有Web开发内容。这是一个运行MariaDB而不是常见的MySQL服务器软件包的Debian 7.1 LAMP堆栈。

昨天我安装了Django并创建了我的第一个项目firstweb。我尚未更改任何设置。

这是我的第一个大困惑。在教程中,我跟随那个家伙安装了Django,开始了他的第一个项目,重新启动了Apache,从那时起Django就开始工作了。他转到浏览器,然后毫无问题地转到Django默认页面。

但是我,我必须进入我的firstweb文件夹并运行

python manage.py runserver myip:port

而且有效。没问题。但是我想知道它是否应该像这样工作,并且这是否会引起问题?

我的第二个问题是我想对其进行设置,以便它使用我的MySQL数据库。我进入/ firstweb / firstweb下的settings.py,看到了ENGINE和NAME,但不确定在这里放什么。

然后在USER,PASSWORD和HOST区域中,这是我的数据库及其凭据吗?如果我使用本地主机,是否可以将本地主机放在HOST区域中?

I want to move away from PHP a little and learn Python. In order to do web development with Python I’ll need a framework to help with templating and other things.

I have a non-production server that I use to test all of web development stuff on. It is a Debian 7.1 LAMP stack that runs MariaDB instead of the common MySQL-server package.

Yesterday I installed Django and created my first project called firstweb. I have not changed any settings yet.

Here is my first big piece of confusion. In the tutorial I followed the guy installed Django, started his first project, restarted Apache, and Django just worked from then on. He went to his browser and went to the Django default page with no problems.

Me however, I have to cd into my firstweb folder and run

python manage.py runserver myip:port

And it works. No problem. But I’m wondering if it is supposed to work like this, and if this will cause problems down the line?

My second question is that I want to set it up so it uses my MySQL database. I go into my settings.py under /firstweb/firstweb and I see ENGINE and NAME but I’m not sure what to put here.

And then in the USER, PASSWORD, and HOST areas is this my database and its credentials? If I am using localhost can I just put localhost in the HOST area?


回答 0

MySQL支持很容易添加。在您的DATABASES字典中,您将有一个像这样的条目:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

从Django 1.7开始,您还可以选择使用MySQL 选项文件。您可以这样设置DATABASES数组来完成此操作:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

您还需要/path/to/my.cnf使用与上面类似的设置来创建文件

[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

使用Django 1.7中的这种新连接方法,重要的是要知道建立了顺序连接:

1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.

换句话说,如果在OPTIONS中设置数据库的名称,它将优先于NAME,而NAME将覆盖MySQL选项文件中的所有内容。


如果您只是在本地计算机上测试应用程序,则可以使用

python manage.py runserver

添加ip:port参数允许您自己的机器以外的其他机器访问您的开发应用程序。准备好部署应用程序后,建议您阅读djangobook上有关部署Django章节

MySQL默认字符集通常不是utf-8,因此请确保使用以下sql创建数据库:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

如果您正在使用Oracle的MySQL的连接器ENGINE线应该是这样的:

'ENGINE': 'mysql.connector.django',

请注意,您首先需要在操作系统上安装mysql。

brew install mysql (MacOS)

此外,mysql客户端软件包已针对python 3进行了更改(MySQL-Client仅适用于python 2)

pip3 install mysqlclient

MySQL support is simple to add. In your DATABASES dictionary, you will have an entry like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES array like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

You also need to create the /path/to/my.cnf file with similar settings from above

[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

With this new method of connecting in Django 1.7, it is important to know the order connections are established:

1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.

In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.


If you are just testing your application on your local machine, you can use

python manage.py runserver

Adding the ip:port argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook

Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

If you are using Oracle’s MySQL connector your ENGINE line should look like this:

'ENGINE': 'mysql.connector.django',

Note that you will first need to install mysql on your OS.

brew install mysql (MacOS)

Also, the mysql client package has changed for python 3 (MySQL-Client works only for python 2)

pip3 install mysqlclient

回答 1

首先,请运行以下命令以安装python依赖项,否则python runserver命令将引发错误。

sudo apt-get install libmysqlclient-dev
sudo pip install MySQL-python

然后配置#Andy定义的settings.py文件,并在最后一次执行:

python manage.py runserver

玩得开心..!!

To the very first please run the below commands to install python dependencies otherwise python runserver command will throw error.

sudo apt-get install libmysqlclient-dev
sudo pip install MySQL-python

Then configure the settings.py file as defined by #Andy and at the last execute :

python manage.py runserver

Have fun..!!


回答 2

如果您使用的是python3.x,则运行以下命令

pip install mysqlclient

然后像这样更改setting.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',
  }
  }

If you are using python3.x then Run below command

pip install mysqlclient

Then change setting.py like

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',
  }
  }

回答 3

如上所述,您可以轻松地首先从https://www.apachefriends.org/download.html安装xampp, 然后按照以下说明进行操作:

  1. http://www.unixmen.com/install-xampp-stack-ubuntu-14-04/安装并运行xampp ,然后从GUI启动Apache Web Server和MySQL数据库。
  2. 您可以根据需要配置Web服务器,但默认情况下Web服务器位于http://localhost:80,数据库位于port 3306,而PhpMyadmin位于http://localhost/phpmyadmin/
  3. 从这里您可以看到您的数据库,并使用非常友好的GUI访问它们。
  4. 创建要在Django项目上使用的任何数据库。
  5. settings.py像这样编辑文件:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DB_NAME',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '',
    }}
  6. 在virtualenv中安装以下软件包(如果您在virtualenv上使用django,则更可取):

    sudo apt-get安装libmysqlclient-dev

    pip安装MySQL-python

  7. 而已!!您已经以非常简单的方式为MySQL配置了Django。

  8. 现在运行您的Django项目:

    python manage.py迁移

    python manage.py运行服务器

As all said above, you can easily install xampp first from https://www.apachefriends.org/download.html Then follow the instructions as:

  1. Install and run xampp from http://www.unixmen.com/install-xampp-stack-ubuntu-14-04/, then start Apache Web Server and MySQL Database from the GUI.
  2. You can configure your web server as you want but by default web server is at http://localhost:80 and database at port 3306, and PhpMyadmin at http://localhost/phpmyadmin/
  3. From here you can see your databases and access them using very friendly GUI.
  4. Create any database which you want to use on your Django Project.
  5. Edit your settings.py file like:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DB_NAME',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '',
    }}
    
  6. Install the following packages in the virtualenv (if you’re using django on virtualenv, which is more preferred):

    sudo apt-get install libmysqlclient-dev

    pip install MySQL-python

  7. That’s it!! you have configured Django with MySQL in a very easy way.

  8. Now run your Django project:

    python manage.py migrate

    python manage.py runserver


回答 4

实际上,不同的环境,python版本等等存在很多问题。您可能还需要安装python dev文件,因此要“强行安装”,我将运行所有这些文件:

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
pip install pymysql
pip install mysqlclient

您应该接受公认的答案。如果对您很重要,可以删除不需要的软件包。

Actually, there are many issues with different environments, python versions, so on. You might also need to install python dev files, so to ‘brute-force’ the installation I would run all of these:

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
pip install pymysql
pip install mysqlclient

You should be good to go with the accepted answer. And can remove the unnecessary packages if that’s important to you.


回答 5

运行这些命令

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python 
pip install pymysql
pip install mysqlclient

然后像这样配置settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_db',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123456',
    }
}

享受mysql连接

Run these commands

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python 
pip install pymysql
pip install mysqlclient

Then configure settings.py like

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_db',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123456',
    }
}

Enjoy mysql connection


回答 6

安迪的答案很有帮助,但是如果您担心要在django设置中公开数据库密码,我建议在mysql连接上遵循django官方配置:https : //docs.djangoproject.com/en/1.7/ref/databases/

在这里引用为:

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}


# my.cnf
[client]
database = NAME
user = USER
password = PASSWORD
default-character-set = utf8

要在设置中替换“ HOST”:“ 127.0.0.1”,只需将其添加到my.cnf中:

# my.cnf
[client]
database = NAME
host = HOST NAME or IP
user = USER
password = PASSWORD
default-character-set = utf8

另一个有用的选项是为django设置存储引擎,您可能需要在setting.py中使用它:

'OPTIONS': {
   'init_command': 'SET storage_engine=INNODB',
}

Andy’s answer helps but if you have concern on exposing your database password in your django setting, I suggest to follow django official configuration on mysql connection: https://docs.djangoproject.com/en/1.7/ref/databases/

Quoted here as:

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}


# my.cnf
[client]
database = NAME
user = USER
password = PASSWORD
default-character-set = utf8

To replace ‘HOST’: ‘127.0.0.1’ in setting, simply add it in my.cnf:

# my.cnf
[client]
database = NAME
host = HOST NAME or IP
user = USER
password = PASSWORD
default-character-set = utf8

Another OPTION that is useful, is to set your storage engine for django, you might want it in your setting.py:

'OPTIONS': {
   'init_command': 'SET storage_engine=INNODB',
}

回答 7

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'django',
    'USER': 'root',
    'PASSWORD': '*****',
    'HOST': '***.***.***.***',
    'PORT': '3306',
    'OPTIONS': {
        'autocommit': True,
    },
}

}

然后:

python manage.py migrate

如果成功将生成这些表:

auth_group
auth_group_permissions
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions
django_admin_log
django_content_type
django_migrations
django_session

您将可以使用mysql。

这是一个展示示例,请在Django 1.11.5版上进行测试: Django-pool-showcase

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'django',
    'USER': 'root',
    'PASSWORD': '*****',
    'HOST': '***.***.***.***',
    'PORT': '3306',
    'OPTIONS': {
        'autocommit': True,
    },
}

}

then:

python manage.py migrate

if success will generate theses tables:

auth_group
auth_group_permissions
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions
django_admin_log
django_content_type
django_migrations
django_session

and u will can use mysql.

this is a showcase example ,test on Django version 1.11.5: Django-pool-showcase


回答 8

  1. 安装 mysqlclient

sudo pip3 install mysqlclient

如果出现错误:

命令“ python setup.py egg_info”在/ tmp / pip-install-dbljg4tx / mysqlclient /中失败,错误代码为1

然后:

 1. sudo apt install libmysqlclient-dev python-mysqldb

 2. sudo pip3 install mysqlclient

  1. 修改settings.py

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'website',
            'USER': 'root',
            'PASSWORD': '',
            'HOST': '127.0.0.1',
            'PORT': '3306',
            'OPTION': {'init_command':"SET sql_mode='STRICT_TRANS_TABLE',"},
        }
    }
  1. Install mysqlclient

sudo pip3 install mysqlclient

if you get error:

Command “python setup.py egg_info” failed with error code 1 in /tmp/pip-install-dbljg4tx/mysqlclient/

then:

 1. sudo apt install libmysqlclient-dev python-mysqldb

 2. sudo pip3 install mysqlclient

  1. Modify settings.py

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'website',
            'USER': 'root',
            'PASSWORD': '',
            'HOST': '127.0.0.1',
            'PORT': '3306',
            'OPTION': {'init_command':"SET sql_mode='STRICT_TRANS_TABLE',"},
        }
    }
    

回答 9

请按照给定的步骤进行设置以使用MySQL数据库:

1) Install MySQL Database Connector :

    sudo apt-get install libmysqlclient-dev

2) Install the mysqlclient library :

    pip install mysqlclient

3) Install MySQL server, with the following command :

    sudo apt-get install mysql-server

4) Create the Database :

    i) Verify that the MySQL service is running:

        systemctl status mysql.service

    ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :  

        mysql -u db_user -p


    iii) CREATE DATABASE db_name;

    iv) Exit MySQL server, press CTRL + D.

5) Add the MySQL Database Connection to your Application:

    i) Navigate to the settings.py file and replace the current DATABASES lines with the following:

        # Database
        # https://docs.djangoproject.com/en/2.0/ref/settings/#databases

        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'OPTIONS': {
                    'read_default_file': '/etc/mysql/my.cnf',
                },
            }
        }
        ...

    ii) Next, lets edit the config file so that it has your MySQL credentials. Use vi as sudo to edit the file and add the following information:

        sudo vi /etc/mysql/my.cnf

        database = db_name
        user = db_user
        password = db_password
        default-character-set = utf8

6) Once the file has been edited, we need to restart MySQL for the changes to take effect :

    systemctl daemon-reload

    systemctl restart mysql

7) Test MySQL Connection to Application:

    python manage.py runserver your-server-ip:8000

Follow the given steps in order to setup it up to use MySQL database:

1) Install MySQL Database Connector :

    sudo apt-get install libmysqlclient-dev

2) Install the mysqlclient library :

    pip install mysqlclient

3) Install MySQL server, with the following command :

    sudo apt-get install mysql-server

4) Create the Database :

    i) Verify that the MySQL service is running:

        systemctl status mysql.service

    ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :  

        mysql -u db_user -p


    iii) CREATE DATABASE db_name;

    iv) Exit MySQL server, press CTRL + D.

5) Add the MySQL Database Connection to your Application:

    i) Navigate to the settings.py file and replace the current DATABASES lines with the following:

        # Database
        # https://docs.djangoproject.com/en/2.0/ref/settings/#databases

        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'OPTIONS': {
                    'read_default_file': '/etc/mysql/my.cnf',
                },
            }
        }
        ...

    ii) Next, let’s edit the config file so that it has your MySQL credentials. Use vi as sudo to edit the file and add the following information:

        sudo vi /etc/mysql/my.cnf

        database = db_name
        user = db_user
        password = db_password
        default-character-set = utf8

6) Once the file has been edited, we need to restart MySQL for the changes to take effect :

    systemctl daemon-reload

    systemctl restart mysql

7) Test MySQL Connection to Application:

    python manage.py runserver your-server-ip:8000

回答 10

您必须首先创建一个MySQL数据库。然后转到settings.py文件并'DATABASES'使用您的MySQL凭据编辑字典:

DATABASES = {
 'default': {
 'ENGINE': 'django.db.backends.mysql',
 'NAME': 'YOUR_DATABASE_NAME',
 'USER': 'YOUR_MYSQL_USER',
 'PASSWORD': 'YOUR_MYSQL_PASS',
 'HOST': 'localhost',   # Or an IP that your DB is hosted on
 'PORT': '3306',
 }
}

这是用于将Django设置为在virtualenv上使用MySQL的完整安装指南:

http://codex.themedelta.com/how-to-install-django-with-mysql-in-a-virtualenv-on-linux/

You must create a MySQL database first. Then go to settings.py file and edit the 'DATABASES' dictionary with your MySQL credentials:

DATABASES = {
 'default': {
 'ENGINE': 'django.db.backends.mysql',
 'NAME': 'YOUR_DATABASE_NAME',
 'USER': 'YOUR_MYSQL_USER',
 'PASSWORD': 'YOUR_MYSQL_PASS',
 'HOST': 'localhost',   # Or an IP that your DB is hosted on
 'PORT': '3306',
 }
}

Here is a complete installation guide for setting up Django to use MySQL on a virtualenv:

http://codex.themedelta.com/how-to-install-django-with-mysql-in-a-virtualenv-on-linux/


没有名为_sqlite3的模块

问题:没有名为_sqlite3的模块

我试图在运行Debian 5的VPS上运行Django应用程序。运行演示应用程序时,它返回此错误:

  File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in     import_module
    __import__(name)

  File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in <module>
    raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc)

ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that     order): No module named _sqlite3

查看Python安装,它给出了相同的错误:

Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in <module>
    from dbapi2 import *
  File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: No module named _sqlite3
>>>

在网上阅读后,我了解到Python 2.5应该附带所有必需的SQLite包装器。我需要重新安装Python,还是有另一种方法来启动和运行此模块?

I am trying to run a Django app on my VPS running Debian 5. When I run a demo app, it comes back with this error:

  File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in     import_module
    __import__(name)

  File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in <module>
    raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc)

ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that     order): No module named _sqlite3

Looking at the Python install, it gives the same error:

Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in <module>
    from dbapi2 import *
  File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: No module named _sqlite3
>>>

Reading on the web, I learn that Python 2.5 should come with all the necessary SQLite wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running?


回答 0

您的makefile文件似乎没有包含适当的.so文件。您可以按照以下步骤纠正此问题:

  1. 安装sqlite-devel(或libsqlite3-dev在某些基于Debian的系统上)
  2. 使用以下命令重新配置和重新编译Python ./configure --enable-loadable-sqlite-extensions && make && sudo make install

注意

sudo make install部分将把python版本设置为系统范围的标准,这可能会产生无法预料的后果。如果您在工作站上运行此命令,则可能希望将其现有python 一起安装,可以使用来完成sudo make altinstall

It seems your makefile didn’t include the appropriate .so file. You can correct this problem with the steps below:

  1. Install sqlite-devel (or libsqlite3-dev on some Debian-based systems)
  2. Re-configure and re-compiled Python with ./configure --enable-loadable-sqlite-extensions && make && sudo make install

Note

The sudo make install part will set that python version to be the system-wide standard, which can have unforseen consequences. If you run this command on your workstation, you’ll probably want to have it installed alongside the existing python, which can be done with sudo make altinstall.


回答 1

我遇到了同样的问题(python2.5从Ubuntu Lucid上的源代码构建),并import sqlite3抛出了同样的异常。我已经libsqlite3-dev从软件包管理器安装了,重新编译了python2.5,然后导入工作了。

I had the same problem (building python2.5 from source on Ubuntu Lucid), and import sqlite3 threw this same exception. I’ve installed libsqlite3-dev from the package manager, recompiled python2.5, and then the import worked.


回答 2

使用pyenv时,我在Ubuntu上的Python 3.5遇到了相同的问题。

如果您使用pyenv安装python ,则将其列为常见的构建问题之一。要解决此问题,请删除已安装的python版本,安装要求(针对此特殊情况libsqlite3-dev),然后重新安装python版本。

I had the same problem with Python 3.5 on Ubuntu while using pyenv.

If you’re installing the python using pyenv, it’s listed as one of the common build problems. To solve it, remove the installed python version, install the requirements (for this particular case libsqlite3-dev), then reinstall the python version.


回答 3

这就是我为使其正常工作所做的。

我正在使用安装了python 2.7.5的pythonbrew(正在使用pip)。

我首先执行了Zubair(上面)所说的,然后运行了以下命令:

sudo apt-get install libsqlite3-dev

然后我运行以下命令:

pip install pysqlite

这解决了数据库问题,我在运行时得到了确认:

python manager.py syncdb

This is what I did to get it to work.

I am using pythonbrew(which is using pip) with python 2.7.5 installed.

I first did what Zubair(above) said and ran this command:

sudo apt-get install libsqlite3-dev

Then I ran this command:

pip install pysqlite

This fixed the database problem and I got confirmation of this when I ran:

python manager.py syncdb

回答 4

  1. 安装sqlite-devel软件包:

    yum install sqlite-devel -y

  2. 从源代码重新编译python:

    ./configure
    make
    make altinstall
  1. Install the sqlite-devel package:

    yum install sqlite-devel -y

  2. Recompile python from the source:

    ./configure
    make
    make altinstall
    

回答 5

我的_sqlite3.so位于/usr/lib/python2.5/lib-dynload/_sqlite3.so中。从您的路径来看,您应该拥有文件/usr/local/lib/python2.5/lib-dynload/_sqlite3.so。

尝试以下方法:

find /usr/local -name _sqlite3.so

如果找不到该文件,则说明您的Python安装可能有问题。如果是,请确保其安装路径在Python路径中。在Python Shell中,

import sys
print sys.path

就我而言,/usr/lib/python2.5/lib-dynload在列表中,因此它可以找到/usr/lib/python2.5/lib-dynload/_sqlite3.so。

My _sqlite3.so is in /usr/lib/python2.5/lib-dynload/_sqlite3.so. Judging from your paths, you should have the file /usr/local/lib/python2.5/lib-dynload/_sqlite3.so.

Try the following:

find /usr/local -name _sqlite3.so

If the file isn’t found, something may be wrong with your Python installation. If it is, make sure the path it’s installed to is in the Python path. In the Python shell,

import sys
print sys.path

In my case, /usr/lib/python2.5/lib-dynload is in the list, so it’s able to find /usr/lib/python2.5/lib-dynload/_sqlite3.so.


回答 6

我最近尝试在Ubuntu 11.04桌面上安装python 2.6.7,以进行一些开发工作。遇到了与此线程类似的问题。我想通过以下方式修复它:

  1. 调整setup.py文件以包含正确的sqlite开发路径。setup.py中的代码片段:

    def sqlite_incdir:
    sqlite_dirs_to_check = [
    os.path.join(sqlite_incdir, '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', 'lib'),
    os.path.join(sqlite_incdir, '..', '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', '..', 'lib'),
    '/usr/lib/x86_64-linux-gnu/'
    ]

    我添加的位是’/ usr / lib / x86_64-linux-gnu /’。

  2. 运行make之后,我没有收到任何警告,提示未构建sqlite支持(即,它正确构建了:P),但是运行后make install,sqlite3仍未使用相同的“ ImportError: No module named _sqlite3" whe running "import sqlite3” 导入。

    因此,该库已编译,但未移至正确的安装路径,因此我复制了该.so文件(cp /usr/src/python/Python-2.6.7/build/lib.linux-x86_64-2.6/_sqlite3.so /usr/local/python-2.6.7/lib/python2.6/sqlite3/这些是我的构建路径,您可能需要根据设置进行调整)。

瞧!现在支持SQLite3。

I recently tried installing python 2.6.7 on my Ubuntu 11.04 desktop for some dev work. Came across similar problems to this thread. I mamaged to fix it by:

  1. Adjusting the setup.py file to include the correct sqlite dev path. Code snippet from setup.py:

    def sqlite_incdir:
    sqlite_dirs_to_check = [
    os.path.join(sqlite_incdir, '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', 'lib'),
    os.path.join(sqlite_incdir, '..', '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', '..', 'lib'),
    '/usr/lib/x86_64-linux-gnu/'
    ]
    

    With the bit that I added being ‘/usr/lib/x86_64-linux-gnu/’.

  2. After running make I did not get any warnings saying the sqlite support was not built (i.e., it built correctly :P ), but after running make install, sqlite3 still did not import with the same “ImportError: No module named _sqlite3" whe running "import sqlite3“.

    So, the library was compiled, but not moved to the correct installation path, so I copied the .so file (cp /usr/src/python/Python-2.6.7/build/lib.linux-x86_64-2.6/_sqlite3.so /usr/local/python-2.6.7/lib/python2.6/sqlite3/ — these are my build paths, you will probably need to adjust them to your setup).

Voila! SQLite3 support now works.


回答 7

我发现很多人都遇到了这个问题,因为在我自己的vps(cent os 7 x64)上,Multi-version Python是通过以下方式解决的:

  1. 找到文件“ _sqlite3.so”

    find / -name _sqlite3.so

    出: /usr/lib64/python2.7/lib-dynload/_sqlite3.so

  2. 找到您要使用的python标准库的目录,

    为了我 /usr/local/lib/python3.6/lib-dynload

  3. 复制文件:

    cp   /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python3.6/lib-dynload

最后,一切都会好的。

I found lots of people meet this problem because the Multi-version Python, on my own vps (cent os 7 x64), I solved it in this way:

  1. Find the file “_sqlite3.so”

    find / -name _sqlite3.so
    

    out: /usr/lib64/python2.7/lib-dynload/_sqlite3.so

  2. Find the dir of python Standard library you want to use,

    for me /usr/local/lib/python3.6/lib-dynload

  3. Copy the file:

    cp   /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python3.6/lib-dynload
    

Finally, everything will be ok.


回答 8

这在Redhat Centos 6.5中对我有用:

yum install sqlite-devel
pip install pysqlite

This worked for me in Redhat Centos 6.5:

yum install sqlite-devel
pip install pysqlite

回答 9

我的python是从源代码构建的,原因是在exec配置python版本时缺少选项:3.7.4

./configure --enable-loadable-sqlite-extensions --enable-optimizations
make
make install

固定

my python is build from source, the cause is missing options when exec configure python version:3.7.4

./configure --enable-loadable-sqlite-extensions --enable-optimizations
make
make install

fixed


回答 10

我在FreeBSD 8.1中有问题:

- No module named _sqlite3 -

通过站立端口解决———-

/usr/ports/databases/py-sqlite3

在此之后可以看到:

OK ----------
'>>>' import sqlite3 -----
'>>>' sqlite3.apilevel -----
'2.0'

I have the problem in FreeBSD 8.1:

- No module named _sqlite3 -

It is solved by stand the port ———-

/usr/ports/databases/py-sqlite3

after this one can see:

OK ----------
'>>>' import sqlite3 -----
'>>>' sqlite3.apilevel -----
'2.0'

回答 11

是否安装了python-pysqlite2软件包?

sudo apt-get install python-pysqlite2

Is the python-pysqlite2 package installed?

sudo apt-get install python-pysqlite2

回答 12

检查您的settings.py文件。您是否不仅为数据库引擎编写了“ sqlite”而不是“ sqlite3”?

Checking your settings.py file. Did you not just write “sqlite” instead of “sqlite3” for the database engine?


回答 13

sqlite3Python附带。我也有同样的问题,我只是卸载python3.6并重新安装了它。

卸载现有的python:

sudo apt-get remove --purge python3.6

安装python3.6:

sudo apt install build-essential checkinstall
sudo apt install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz
tar xvf Python-3.6.0.tar.xz
cd Python-3.6.0/
./configure
sudo make altinstall

sqlite3 ships with Python. I also had the same problem, I just uninstalled python3.6 and installed it again.

Uninstall existing python:

sudo apt-get remove --purge python3.6

Install python3.6:

sudo apt install build-essential checkinstall
sudo apt install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz
tar xvf Python-3.6.0.tar.xz
cd Python-3.6.0/
./configure
sudo make altinstall

回答 14

您必须使用centos或redhat并自己编译python,这是python的错误,请在python源代码目录中执行此操作,并在下面执行此操作

curl -sk https://gist.github.com/msabramo/2727063/raw/59ea097a1f4c6f114c32f7743308a061698b17fd/gistfile1.diff | patch -p1

you must be in centos or redhat and compile python yourself, it is python‘s bug do this in your python source code dir and do this below

curl -sk https://gist.github.com/msabramo/2727063/raw/59ea097a1f4c6f114c32f7743308a061698b17fd/gistfile1.diff | patch -p1

回答 15

我遇到了同样的问题,上述问题对我没有任何帮助,但是现在我通过

只是删除python.pipsqlite3并重新安装

  1. sudo apt-get remove python.pip
  2. sudo apt-get remove sqlite3

现在再次安装

  1. sudo apt-get install python.pip
  2. sudo apt-get install sqlite3

在我的情况下sqlite3再次安装时它显示了一些错误,然后我键入

  1. sqlite3

在终端上检查是否已卸下,然后开始拆箱

一旦sqlite3安装了启动终端并写入

  1. sqlite3
  2. database.db (创建数据库)

我相信这一定会对您有帮助

I got the same problem, nothing worked for me from the above ans but now I fixed it by

just remove python.pip and sqlite3 and reinstall

  1. sudo apt-get remove python.pip
  2. sudo apt-get remove sqlite3

now install it again

  1. sudo apt-get install python.pip
  2. sudo apt-get install sqlite3

in my case while installing sqlite3 again it showed some error then I typed

  1. sqlite3

on terminal to check if it was removed or not and it started unpacking it

once the sqlite3 is installed fireup terminal and write

  1. sqlite3
  2. database.db (to create a database)

I’m sure this will definitely help you


回答 16

为登录此页面的任何人提供答案,以寻找适用于Windows OS的解决方案:

如果尚未安装pysqlite3或db-sqlite3,则必须安装。您可以使用以下安装。

  • pip安装pysqlite3
  • pip安装db-sqlite3

对我来说,问题在于sqlite3的DLL文件。

解:

  1. 我从sqlite网站上获取了DLL文件。这可能会因您安装的python版本而异。

  2. 我将其粘贴到env的DLL目录中。对我来说,它是“ C:\ Anaconda \ Lib \ DLLs”,但请检查您的。

Putting answer for anyone who lands on this page searching for a solution for Windows OS:

You have to install pysqlite3 or db-sqlite3 if not already installed. you can use following to install.

  • pip install pysqlite3
  • pip install db-sqlite3

For me the issue was with DLL file of sqlite3.

Solution:

  1. I took DLL file from sqlite site. This might vary based on your version of python installation.

  2. I pasted it in the DLL directory of the env. for me it was “C:\Anaconda\Lib\DLLs”, but check for yours.


回答 17

令我感到失望的是,这个问题一直存在到今天。由于我最近一直在尝试在CentOS 8.1上安装vCD CLI,因此在尝试运行它时出现相同的错误,对此我表示欢迎。在我的情况下,我必须解决的方法如下:

  • 使用适当的前缀从头开始安装SQLite3
  • 清理我的Python安装
  • 运行Make install重新安装Python

正如我一直在做的那样,以创建有关如何安装vCD CLI和VMware Container Service Extension的不同博客文章。我最终捕获了用于解决此问题的步骤,并将其放在单独的博客文章中,网址为:

http://www.virtualizationteam.com/cloud/running-vcd-cli-fail-with-the-following-error-modulenotfounderror-no-module-named-_sqlite3.html

我希望这会有所帮助,因为尽管上面的提示帮助我找到了解决方案,但我不得不将其中的几个结合起来并进行一些修改。

I was disappointed this issue still exist till today. As I have recently been trying to install vCD CLI on CentOS 8.1 and I was welcomed with the same error when tried to run it. The way I had to resolve it in my case is as follow:

  • Install SQLite3 from scratch with the proper prefix
  • Make clean my Python Installation
  • Run Make install to reinstall Python

As I have been doing this to create a different blogpost about how to install vCD CLI and VMware Container Service Extension. I have end up capturing the steps I used to fix the issue and put it in a separate blog post at:

http://www.virtualizationteam.com/cloud/running-vcd-cli-fail-with-the-following-error-modulenotfounderror-no-module-named-_sqlite3.html

I hope this helpful, as while the tips above had helped me get to a solution, I had to combine few of them and modify them a bit.


回答 18

下载sqlite3:

wget http://www.sqlite.org/2016/sqlite-autoconf-3150000.tar.gz

请按照以下步骤进行安装:

$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make install

Download sqlite3:

wget http://www.sqlite.org/2016/sqlite-autoconf-3150000.tar.gz

Follow these steps to install:

$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make install

回答 19

您需要在python环境中安装pysqlite

    $ pip install pysqlite

You need to install pysqlite in your python environment:

    $ pip install pysqlite

回答 20

尝试复制 _sqlite3.so以便Python可以找到它。

它应该很简单:

cp /usr/lib64/python2.6/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/

相信我,尝试一下。

Try copying _sqlite3.so so that Python can find it.

It should be as simple as:

cp /usr/lib64/python2.6/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/

Trust me, try it.


python-dev安装错误:ImportError:没有名为apt_pkg的模块

问题:python-dev安装错误:ImportError:没有名为apt_pkg的模块

我是Debian用户,我想安装python-dev,但是当我以root身份在shell中运行代码时:

# aptitude install python-dev

我收到以下错误:

Traceback (most recent call last):       
  File "/usr/bin/apt-listchanges", line 28, in <module>
    import apt_pkg
ImportError: No module named apt_pkg

似乎是什么问题,我该如何解决?

I am Debian user, and I want to install python-dev, but when I run the code in the shell as a root:

# aptitude install python-dev

I get the following error:

Traceback (most recent call last):       
  File "/usr/bin/apt-listchanges", line 28, in <module>
    import apt_pkg
ImportError: No module named apt_pkg

What seems to be the problem and how can I resolve it?


回答 0

确保您有一个有效的python-apt软件包。您可以尝试再次删除并安装该软件包以解决apt_pkg.so的问题。

apt-get install python-apt

Make sure you have a working python-apt package. You could try and remove and install that package again to fix the problem with apt_pkg.so not being located.

apt-get install python-apt

回答 1

我在做的时候遇到了这个问题sudo apt-get update。我的环境是debian8,python2.7 + 3.4(默认)+ 3.5。

以下代码将仅为apt_pkg....sopython 3.5重新创建文件

sudo apt-get install python3-apt --reinstall

以下代码解决了我的问题,

cd /usr/lib/python3/dist-packages
sudo ln -s apt_pkg.cpython-{35m,34m}-x86_64-linux-gnu.so

因此,很显然,python3-apt会检查最高的python版本,而不是当前使用的python版本。

I met this problem when doing sudo apt-get update. My env is debian8, with python2.7 + 3.4(default) + 3.5.

The following code will only re-create a apt_pkg....so file for python 3.5

sudo apt-get install python3-apt --reinstall

The following code solved my problem,

cd /usr/lib/python3/dist-packages
sudo ln -s apt_pkg.cpython-{35m,34m}-x86_64-linux-gnu.so

So, obviously, python3-apt checks the highest python version, instead of the current python version in use.


回答 2

通过以下方法解决:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-34m-i386-linux-gnu.so apt_pkg.so

要么:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so

基本上,如果您No such file or directory公正ls地尝试获得正确的名字。

Solve it by this:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-34m-i386-linux-gnu.so apt_pkg.so

Or:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so

Basically, if you get a No such file or directory just ls to try to get the right name.


回答 3

在我尝试从Deadsnakes存储库中安装Python3.7之后,在Ubuntu 18.04.2上发生了这种情况。

解决方法是这个

1) cd /usr/lib/python3/dist-packages/

2) sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

This happened to me on Ubuntu 18.04.2 after I tried to install Python3.7 from the deadsnakes repo.

Solution was this

1) cd /usr/lib/python3/dist-packages/

2) sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so


回答 4

当同时安装了新版本的python和旧版本时,通常会发生此错误。

  • Ubuntu 18.04.1随附python版本3.6.6
  • 已安装ppa:deadsnakes / python3.7.1或替代版本
  • 运行使用apt_pkg模块的命令,并显示诸如以下错误:

        from CommandNotFound.db.db import SqliteDatabase
    File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
        import apt_pkg
    

当我们安装带有apt的非发行版python3版本时,会将共享模块目录设置为python3的共享目录,通常是/usr/lib/python3

在大多数情况下,这是可以的,但是在某些情况下,不同版本的python会比其他python版本依赖不同的库或共享对象/库,因此正如其他答案所指出的那样,我们需要将.SO链接到正确的python版本。因此,如果我们在64位系统上安装了python3.6,则apt_pkg .SO链接为

sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

但是问题在于,当我们安装较新的python版本时,链接将更新为指向最新的python版本,这将导致找不到apt_pkg模块的错误。通过检查发行版附带的python版本,您可以创建上述链接。或者,我们使用一种方法来为命令提供选择python版本以链接.SO的选择,例如;

sudo ln -s apt_pkg.cpython-{36m,35m,34m}-x86_64-linux-gnu.so apt_pkg.so

因为python会创建到最新安装的python版本的链接,所以我们给命令提供了从3个python版本中进行选择的选项,它将选择给定的最高版本。

This error will often occur when a newer version of python has been installed alongside an older version e.g;

  • Ubuntu 18.04.1 ships with python version 3.6.6
  • Installed ppa:deadsnakes/python3.7.1 or alternative
  • Run a command that uses the apt_pkg module and get an error such as;

        from CommandNotFound.db.db import SqliteDatabase
    File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
        import apt_pkg
    

When we install a non-distro python3 version with apt it will set a shared module directory to be that of python3 most usually it will be /usr/lib/python3.

Most of the time this will be ok, but under some circumstances the different versions of python rely on different libraries or shared objects/libraries than the other python version does, so as other answers have pointed out we need to link the .SO to the correct python version. So if we have python3.6 installed on a 64bit system then the apt_pkg .SO link would be

sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

But the problem lies in the fact that when we install a newer python version the link will update to point to the newest python version, which leads to the error of apt_pkg module not being found. By checking which version of python ships with your distro you can create the link as shown above. Or we use a method to offer the command a choice of python versions to link the .SO such as;

sudo ln -s apt_pkg.cpython-{36m,35m,34m}-x86_64-linux-gnu.so apt_pkg.so

Because python will create this link to the newest installed python version we give the command the option to choose from 3 python versions, of which it will choose the highest version given.


回答 5

@ user8178061的解决方案效果很好,但是我对python3.7Ubuntu的版本做了一些修改

我更换了apt_pkg.cpython-3m-i386-linux-gnu.soapt_pkg.cpython-36m-x86_64-linux-gnu.so

这里执行两个命令:

cd /usr/lib/python3/dist-packages

sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

The solution of @user8178061 worked well but I did it with some modifications for my version wich is python3.7 with Ubuntu

I replaced the apt_pkg.cpython-3m-i386-linux-gnu.so with apt_pkg.cpython-36m-x86_64-linux-gnu.so

Here the two commands to execute:

cd /usr/lib/python3/dist-packages

sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so


回答 6

在ubuntu18.04上更新python3.7之后,这对我有用

cd /usr/lib/python3/dist-packages
sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

This worked for me on after updating python3.7 on ubuntu18.04

cd /usr/lib/python3/dist-packages
sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

回答 7

由于某种原因apt_pkg.so,python3 dist-packages目录中缺少我的安装。(apt_pkg.cpython-33m-x86_64-linux-gnu.so在那里?!),但是,我不得不作出一个符号链接apt_pkg.so -> apt_pkg.cpython-33m-x86_64-linux-gnu.so/usr/lib/python3/dist-packages

我不确定我的升级是否中断,或者为什么会这样。尝试升级后发生(精确-> raring->定量升级)

For some reason my install was missing apt_pkg.so in the python3 dist-packages dir. (apt_pkg.cpython-33m-x86_64-linux-gnu.so was there?!) but and I had to make a symlink apt_pkg.so -> apt_pkg.cpython-33m-x86_64-linux-gnu.so in /usr/lib/python3/dist-packages

I’m not sure whether my upgrade was broken or why this was the case. It occured after trying to upgrade (precise->raring->quantal upgrade)


回答 8

  1. 检查您的默认Python 3版本:
python --version
Python 3.7.5
  1. cd进入/usr/lib/python3/dist-packages并检查apt_pkg.*文件。您会发现默认Python版本没有:
ll apt_pkg.*
apt_pkg.cpython-36m-x86_64-linux-gnu.so
  1. 创建符号链接:
sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.cpython-37m-x86_64- linux-gnu.so 
  1. Check your default Python 3 version:
python --version
Python 3.7.5
  1. cd into /usr/lib/python3/dist-packages and check the apt_pkg.* files. You will find that there is none for your default Python version:
ll apt_pkg.*
apt_pkg.cpython-36m-x86_64-linux-gnu.so
  1. Create the symlink:
sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.cpython-37m-x86_64- linux-gnu.so 

回答 9

不得已的方法是,sudo cp /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so /usr/lib/python3/dist-packages/apt_pkg.cpython-36m-x86_64-linux-gnu.so 如果该ln命令对您来说太多了,或者由于某种原因魔术无法正常工作。

cpmv如果您仅致力于使用一个Python版本,则也可以使用上述方法。

A last resort is sudo cp /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so /usr/lib/python3/dist-packages/apt_pkg.cpython-36m-x86_64-linux-gnu.so if the ln command is too much for you or somehow magically doesn’t work.

cp above can also be mv if you are only dedicated to using one Python version.


回答 10

如果您使用的是python 3.7,请通过更新Alternatives将其降级为python 3.6,这对我有用

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1

sudo update-alternatives --config python3

if you’re using python 3.7 downgrade it to python 3.6 by updating Alternatives, This worked for me

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1

sudo update-alternatives --config python3

回答 11

如果您使用的是Python 3.5,请降级为3.4。这是最安全的举动。

在下面,/usr/lib/python3/dist-packages您将看到*34m*不能使用哪个python 3.5。zhazha回答了它的符号链接。

If you’re using python 3.5, downgrade to 3.4. That’s the safest move to do.

Under /usr/lib/python3/dist-packages you’ll see *34m* which python 3.5 can’t use. zhazha answer symlink to it.


回答 12

除了为其建立符号链接外apt_pkg.so,您可能还希望以与之apt_inst.so相同的方式进行apt_pkg.so

ln -s apt_inst.cpython-35m-x86_64-linux-gnu.so apt_inst.so 

In addition to making a symbolic link for apt_pkg.so, you may want to make apt_inst.so in the same manner of apt_pkg.so.

ln -s apt_inst.cpython-35m-x86_64-linux-gnu.so apt_inst.so 

回答 13

我看到每个人都在说如何通过奇怪的复制等方式修复它,但是没人真正说出为什么会出现此问题。

因此,让我解释一下,对于像我这样的人,不想仅仅因为SO上的某人告诉了他们而弄乱系统文件。


问题是:

  • 许多系统脚本都将python3 shebang硬编码到其中。您可以自己检查:
~$ grep -R "\#\!/usr/bin/python3" /usr/lib/*

/usr/lib/cnf-update-db:#!/usr/bin/python3
/usr/lib/command-not-found:#!/usr/bin/python3
/usr/lib/cups/filter/pstotiff:#!/usr/bin/python3
/usr/lib/cups/filter/rastertosag-gdi:#!/usr/bin/python3 -u
grep: /usr/lib/cups/backend/cups-brf: Permission denied
/usr/lib/cups/backend/hpfax:#!/usr/bin/python3
/usr/lib/language-selector/ls-dbus-backend:#!/usr/bin/python3
/usr/lib/python3/dist-packages/language_support_pkgs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/softwareproperties/MirrorTest.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/installdriver.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/openprinting.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/xmldriverprefs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/smburi.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/ppds.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/debug.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/DistUpgrade/dist-upgrade.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/db.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/Quirks/quirkreader.py:#!/usr/bin/python3
grep: /usr/lib/ssl/private: Permission denied
/usr/lib/system-service/system-service-d:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release-gtk:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/do-partial-upgrade:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release:#!/usr/bin/python3
/usr/lib/update-notifier/package-data-downloader:#!/usr/bin/python3
/usr/lib/update-notifier/backend_helper.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt_check.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt-check:#!/usr/bin/python3

  • python apt package python-apt/python3-apt是系统软件包,因此它是默认系统python

因此,这些脚本将始终获得当前链接到的版本python3,但是由于apt软件包不存在而失败。


常规解决方案:永远不要更改默认python3链接。曾经 这也适用于python链接-如果应用程序是使用Python2编写的,但其中的某些旧语法元素在Python3中不起作用,则该应用程序将无法工作。

[我的终端打破了这种方式,因为我使用了终结者,终结者显然是用Python2.7编写的,与Python3不兼容。]


这里介绍的解决方案建议复制/链接apt软件包文件或更改python3链接。

让我们分析一下:

  1. 复制/链接apt包

应该不是问题,因为从Python3.4开始,所有python脚本也都可以在较新的版本上运行。

至今。但是,如果您将系统保留足够长的时间,将来可能会中断。

  1. python3回链接

这是一个很好的解决方案,因为我们可以回到“从不更改链接”


“但是我喜欢只打python!” – 我也喜欢这个!这就是我首先解决这个问题的方法!

  1. 通常,应该避免手动更改系统链接-update-alternatives而是使用它来链接不同的版本。这适用于具有多个版本的任何应用。这仍然会破坏那些系统脚本(因为它确实会更改链接),但是您可以轻松地来回切换,而不必担心将链接和目标按正确的顺序放置或输入错误。

  2. 考虑为链接或别名使用python/以外的其他名称python3

  3. 或将自己的python/python3链接添加到PATH(就像虚拟环境一样),而无需更改系统链接。

I see everyone saying how to fix it with strange copying etc, but no one really said why the problem occurs.

So let me explain, for those of you who like me don’t want to mess with system files only because someone on SO told them so.


The problem is that:

  • many system scripts have python3 shebang hardcoded into them. You can check it yourself:
~$ grep -R "\#\!/usr/bin/python3" /usr/lib/*

/usr/lib/cnf-update-db:#!/usr/bin/python3
/usr/lib/command-not-found:#!/usr/bin/python3
/usr/lib/cups/filter/pstotiff:#!/usr/bin/python3
/usr/lib/cups/filter/rastertosag-gdi:#!/usr/bin/python3 -u
grep: /usr/lib/cups/backend/cups-brf: Permission denied
/usr/lib/cups/backend/hpfax:#!/usr/bin/python3
/usr/lib/language-selector/ls-dbus-backend:#!/usr/bin/python3
/usr/lib/python3/dist-packages/language_support_pkgs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/softwareproperties/MirrorTest.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/installdriver.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/openprinting.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/xmldriverprefs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/smburi.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/ppds.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/debug.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/DistUpgrade/dist-upgrade.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/db.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/Quirks/quirkreader.py:#!/usr/bin/python3
grep: /usr/lib/ssl/private: Permission denied
/usr/lib/system-service/system-service-d:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release-gtk:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/do-partial-upgrade:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release:#!/usr/bin/python3
/usr/lib/update-notifier/package-data-downloader:#!/usr/bin/python3
/usr/lib/update-notifier/backend_helper.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt_check.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt-check:#!/usr/bin/python3

  • python apt package python-apt/python3-apt is a system package, so it’s for default system python

Thus, the scripts will always get the version currently linked to python3, but fail because the apt package is not present.


General solution: NEVER change default python3 link. Ever. This also applies to python link – if an app was written in Python2 with some old syntax elements that don’t work in Python3, the app will not work.

[My terminal broke that way because I use Terminator, which is apparently written in Python2.7 not compatible with Python3.]


Solutions presented here either suggest copying/linking the apt package files or changing python3 link.

Let’s analyse both:

  1. Copying/linking the apt package

This shouldn’t be a problem because from around Python3.4 all python scripts work on newer versions as well.

So far. But it may break in the future – if you keep your system long enough.

  1. Changing python3 link back

This is a great solution because we can get back to “never ever changing the link”


“But I like having to type just python!” – I like it too! That’s how I got to this problem in the first place!

  1. In general, you should avoid manually changing system links – use update-alternatives instead to link different versions. This applies to any app with many versions. This will still break those system scripts (because it does change the link), but you can switch back and forth easily, without worrying whether you put link and dest in the right order or made a typo.

  2. Consider using other name than python/python3 for your link or alias.

  3. Or add your own python/python3 link to PATH (just like virtual environments do), without changing system links.


回答 14

Windows 10 WSL v1(Ubuntu 16.04.6 LTS)

这个reddit答案(稍加修改对我有用

sudo ln -sfn /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so

Windows 10 WSL v1 (Ubuntu 16.04.6 LTS)

This reddit answer (slightly modified worked for me)

sudo ln -sfn /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so


回答 15

请查看以下文档。肯定会解决问题。 http://www.programmersought.com/article/55001874709/

Please review the following documentation. It will definitely solve the problem. http://www.programmersought.com/article/55001874709/


回答 16

没有一个答案对我有用(我正在使用Ubuntu 16.04和Python 3.6)。因此,我终于解决了以下问题:

1-连接到服务器的FTP

2-转到文件夹“ / usr / lib / python3 / dist-packages /”

3-复制文件“ apt_pkg.cpython-3 5 m-x86_64-linux-gnu.so”

4-将此重复文件重命名为“ apt_pkg.cpython-3 6 m-x86_64-linux-gnu.so”

而已!

None of the answers worked for me (I am using Ubuntu 16.04 and Python 3.6). So I finally solved the issue as following:

1- connect to the FTP of the server

2- go to the folder “/usr/lib/python3/dist-packages/”

3- duplicate the file “apt_pkg.cpython-35m-x86_64-linux-gnu.so”

4- rename this duplicated file to “apt_pkg.cpython-36m-x86_64-linux-gnu.so”

That’s it!


回答 17

我在Ubuntu 16.04上,并已升级到Python 3.7。这是我尝试添加PPA时遇到的错误

    sudo add-apt-repository ppa:ubuntu-toolchain-r/test                                           
Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 11, in <module>
    from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 27, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

我可以通过创建以下符号链接来与我的初始python 3.4 apt_pkg.cpython-34m-x86_64-linux-gnu.so建立符号链接来解决此错误

sudo ln -s apt_pkg.cpython-34m-x86_64-linux-gnu.so apt_pkg.so

I’m on Ubuntu 16.04, and upgraded to Python 3.7. Here is the error that I had when trying to add a PPA

    sudo add-apt-repository ppa:ubuntu-toolchain-r/test                                           
Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 11, in <module>
    from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 27, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

I was able to fix this error by making symbolic link with my initial python 3.4 apt_pkg.cpython-34m-x86_64-linux-gnu.so by creating the following symbolic link

sudo ln -s apt_pkg.cpython-34m-x86_64-linux-gnu.so apt_pkg.so

回答 18

请尝试通过设置区域设置变量来解决此问题:

export LC_ALL="en_US.UTF-8"

export LC_CTYPE="en_US.UTF-8"

Please try to fix this by setting the locale variables:

export LC_ALL="en_US.UTF-8"

export LC_CTYPE="en_US.UTF-8"

回答 19

以防万一,这终于解决了这个问题,这显然是python版本冲突所致,方法是重定向链接python3,然后将其重定向到正确的python版本:

sudo rm /usr/bin/python3
sudo ln -s /usr/bin/python3.4

您可能需要输入正确的python版本,找到以下版本:

python3 -V

Just in case it helps another, I finally solved this problem, that was apparently caused by python version conflicts, by redirecting the link python3, then redirecting it to the right python version:

sudo rm /usr/bin/python3
sudo ln -s /usr/bin/python3.4

You may need to enter the correct python version, found with:

python3 -V