Python学习---问题集

问题: win 系统下,python3+环境,写一个购物车程序,退出时打印商品价格,执行后报错信息如下

         Traceback (most recent call last):

         File "H:/Python培训/2017-09-14/Shopping Cart.py", line 6, in <module>

         print("您选择的商品价格为:"+prices[buy+1])

         TypeError: must be str, not int

        答案:字符串不能跟整型合并,把需要合并的整型用str转换成字符串即可。

问题: win 系统下,python3+环境,在创建一个嵌套的字典时,执行后报错信息如下

         "C:\Program Files\Python\Python36\python.exe" H:/Python培训/2017-09-18/level3.py

          File "H:/Python培训/2017-09-18/level3.py", line 2

         "福建省"{"福州"{"仓山区","晋安区","台江区"},

                    ^

         SyntaxError: invalid syntax

        答案:键跟值之间必须要使用:隔开,加上:即可。

问题: win 系统下,python3+环境,在读取一个嵌套的字典时,执行后报错信息如下

   Traceback (most recent call last):

   File "H:/Python培训/2017-09-18/level3.py", line 14, in <module>

   for i2 in level(choice1):

   TypeError: 'dict' object is not callable

          答案:字典取键的值时应该使用[]而不是(),()改成[]即可。

问题: win 系统下,python3+环境,在引用一个变量时,执行后报错信息如下

   Traceback (most recent call last):

   File "H:/Python培训/2017-09-19/shopping car.py", line 22, in <module>

   print(seller_username)

   NameError: name 'seller_username' is not defined

         答案:引用了一个不存在的变量,引用前需要先定义变量。

问题: win 系统下,python3+环境,在调用一个列表的值时,执行后报错信息如下

   Traceback (most recent call last):

   File "H:/Python培训/2017-09-19/shopping car.py", line 26, in <module>

   if user_password == user_password_list(user_list.index(user_name)):

   TypeError: 'list' object is not callable

          答案:取列表的值时应该使用[]而不是(),把()换成[]即可。

问题: win 系统下,python3+环境,在执行一个if..else语句时,执行后报错信息如下

          "C:\Program Files\Python\Python36\python.exe" "H:/Python培训/2017-09-19/shopping car.py"

           File "H:/Python培训/2017-09-19/shopping car.py", line 40

           elif choice == "q":

                                   ^

          IndentationError: expected an indented block

        答案:if语句下面的代码块没写就运行,代码块没写时可使用pass语句

问题: win 系统下,python3+环境,choice接收input的输入,执行后报错信息如下

        Traceback (most recent call last):

        File "H:/Python培训/2017-09-19/shopping car.py", line 40, in <module>

        if choice >=0 and choice<len(goods_list):

       TypeError: '>=' not supported between instances of 'str' and 'int'

      答案:数据类型错误,input输入的为字符串,字符串无法跟整型比较,使用int将字符串转换成整型即可。

问题: win 系统下,python3+环境,进行文件操作时,执行后报错信息如下

           Traceback (most recent call last):

           File "H:/Python培训/2017-09-19/shopping car.py", line 56, in <module>

           ba.write(bala)

           TypeError: write() argument must be str, not int

          答案:write写入必须为字符串,不能为整型,使用str将整型转换为字符串即可。

问题: win 系统下,python3+环境,使用split函数时,执行后报错信息如下

           File "H:/Python培训/1.第一模块/作业/模拟登陆/login.py", line 6

           x = line1.strip().split(,)

                                         ^

          SyntaxError: invalid syntax

         答案:split中的参数为字符串类型,必须加引号。

问题: win 系统下,python3+环境,写一个程序进行文件操作,读取文件时,执行后报错信息如下

          Traceback (most recent call last):

          File "H:/Python培训/1.第一模块/作业/三级菜单/level3.py", line 2, in <module>

          for line in f:

          io.UnsupportedOperation: not readable

         答案:打开文件时使用的是“a”追加模式,无法读取文件,将打开模式改为“r”即可。

问题: win 系统下,python3+环境,for循环一个字典时,执行后报错信息如下

            File "H:/Python培训/1.第一模块/作业/三级菜单/level3.py", line 18

            for y in level[choice]

                                          ^

            SyntaxError: invalid syntax

          答案:for循环语句末尾忘记加:,加上:即可。

问题: win 系统下,python3+环境,写一个程序对文件进行操作,返回文件大小时,执行后报错信息如下

           Traceback (most recent call last):

           File "H:/Python培训/1.第一模块/作业/购物车/shopping.py", line 22, in <module>

           if os.path.getsize() == 0:

           TypeError: getsize() missing 1 required positional argument: 'filename'

          答案:os.path.getsize()的参数必须为具体的文件,指定具体的文件即可。

问题: win 系统下,python3+环境下,对使用列表下标读取列表中的值时,执行后报错信息如下:

         Traceback (most recent call last):
         File "H:/Python培训/2.第二模块/作业/员工信息系统/staff_info_test.py", line 93, in <module>
              if update[-1].replace('"', "") == update_list[4]:
         IndexError: list index out of range
         答案:在取值时读取了错误的列表,下标超过了该列表的长度,读取正确的列表即可

问题: win 系统下,python3+环境下,使用isinstance()函数判断列表是否是可迭代对象时,执行后报错信息如下:

>>> isinstance([],Iterable)

       Traceback (most recent call last):

          File "<stdin>", line 1, in <module>

       NameError: name 'Iterable' is not defined

       答案:需要导入Iterable模块,执行from collections import Iterable即可

问题: win 系统下,python3+环境下,定义函数时使用非固定参数,执行后报错信息如下:

         Traceback (most recent call last):

          File "H:/Python培训/2.第二模块/2017-10-13/test1.py", line 22, in <module>

             user()

          File "H:/Python培训/2.第二模块/2017-10-13/test1.py", line 3, in deco

             func(args, kwargs)

         TypeError: user() takes 0 positional arguments but 2 were given

         答案:函数中调用非固定参数时也必须使用*args,**kwargs的写法,错误中的func(args,kwargs)改成func(*args,**kwargs)即可

问题: win 系统下,python3+环境下,调用自定义模块时,执行后报错信息如下:

       Traceback (most recent call last):

       File "H:/Python培训/2.第二模块/作业/ATM/atm/bin/atm.py", line 6, in <module>

       from core import main

     ModuleNotFoundError: No module named 'core'

    答案:忘记将模块所在路径加入path,使用sys.path.append将路径加入path即可

问题: win 系统下,python3+环境下,调用自定义模块时,执行后报错信息如下:

         Traceback (most recent call last):

          File "H:/Python培训/2.第二模块/作业/ATM/atm/bin/manage.py", line 10, in <module>

           main.manage_run()

         File "H:\Python培训\2.第二模块\作业\ATM\atm\core\login.py", line 21, in login

          logger.managelog(admin_name, "login", "success")

        AttributeError: module 'core.logger' has no attribute 'managelog'

      答案:调用时写错了函数名,改成正确的即可

问题: win 系统下,python3+环境下,打开一个文件进行操作时,执行后报错信息如下:

          Traceback (most recent call last):

          File "H:/Python培训/2.第二模块/作业/ATM/atm/bin/manage.py", line 7, in <module>

           from core import main

          File "H:\Python培训\2.第二模块\作业\ATM\atm\core\main.py", line 25, in <module>

          from core import manage_function

         File "H:\Python培训\2.第二模块\作业\ATM\atm\core\manage_function.py", line 8, in <module>

           with open("%s/log/manage.log", "r") as f1:

        FileNotFoundError: [Errno 2] No such file or directory: '%s/log/manage.log'

       答案:忘记定义对%s进行定义,定义%s即可

问题: win 系统下,python3+环境下,写一个还款后计算剩余未还款金额的程序时,执行后报错信息如下:

          Traceback (most recent call last):

          File "H:/Python培训/2.第二模块/作业/ATM/atm/bin/atm.py", line 10, in <module>

           main.user_run()

          File "H:\Python培训\2.第二模块\作业\ATM\atm\core\login.py", line 40, in login

           func(*args, **kwargs)

          File "H:\Python培训\2.第二模块\作业\ATM\atm\core\main.py", line 49, in user_run

           user_choice_list[user_choice]() # 根据选择的功能执行相应的函数

          File "H:\Python培训\2.第二模块\作业\ATM\atm\core\main.py", line 23, in repayment

           user_function.repayment_function()

          File "H:\Python培训\2.第二模块\作业\ATM\atm\core\user_function.py", line 59, in repayment_function

            print("本月已还款%s,还需还款%s" % (repayment_sum, repayment_must - repayment_sum))

         TypeError: unsupported operand type(s) for -: 'float' and 'str'

         答案:两个变量相减时忘记转换数据类型,将一个变量的类型从字符串转成浮点型即可

问题: win 系统下,python3+环境下,调用一个装饰器时,执行后报错信息如下:

         Traceback (most recent call last):

          File "H:/Python培训/2.第二模块/作业/ATM/shopping_mall/bin/shopping_mall.py", line 7, in <module>

           from core import main

          File "H:\Python培训\2.第二模块\作业\ATM\shopping_mall\core\main.py", line 9, in <module>

           @auth()

         TypeError: auth() missing 1 required positional argument: 'func'

         答案:调用装饰器时写成@auth(),调用时应该指向的是该装饰器的内存地址,把@auth后面的括号去掉即可

问题: win 系统下,python3+环境下,在读取一个json文件时,执行后报错信息如下:

          Traceback (most recent call last):

          File "H:/Python培训/2.第二模块/作业/ATM/shopping_mall/core/mall_function.py", line 7, in <module>

           good_list = json.load(f)

          File "C:\Program Files\Python\Python36\lib\json\__init__.py", line 299, in load

          parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

         File "C:\Program Files\Python\Python36\lib\json\__init__.py", line 354, in loads

          return _default_decoder.decode(s)

        File "C:\Program Files\Python\Python36\lib\json\decoder.py", line 339, in decode

         obj, end = self.raw_decode(s, idx=_w(s, 0).end())

        File "C:\Program Files\Python\Python36\lib\json\decoder.py", line 355, in raw_decode

        obj, end = self.scan_once(s, idx)

        json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 66 (char 65)

      答案:json文件中的列表少了一个逗号,修改json文件即可

问题: win 系统下,python3+环境下,在使用正则模块进行匹配时,执行后报错信息如下:

         Traceback (most recent call last):

          File "<stdin>", line 1, in <module>

          NameError: name 're' is not defined

         答案:忘记导入re模块,import re即可

问题: win 系统下,python3+环境下,写一个子类继承一个基类时,执行后报错信息如下:

          Traceback (most recent call last):

          File "H:/Python培训/3.第三模块/2017-10-31/class_test3.py", line 27, in <module>

          d = Husky("二哈", "2")

         File "H:/Python培训/3.第三模块/2017-10-31/class_test3.py", line 20, in __init__

          super(Dog, self).__init__(name, age)

        TypeError: object.__init__() takes no parameters

       答案:super()中的类写成基类,改为子类即可

问题: win 系统下,python3+环境下,写一个子类继承一个基类时,执行后报错信息如下:

         Traceback (most recent call last):

         File "H:/Python培训/3.第三模块/2017-10-31/class_test3.py", line 27, in <module>

         d = Husky("二哈", "2")

         File "H:/Python培训/3.第三模块/2017-10-31/class_test3.py", line 22, in __init__

         Dog.add_dog()

        TypeError: add_dog() missing 1 required positional argument: 'self'

        答案:调用基类的方法时少了self,加上self即可

问题: win 系统下,python3+环境下,写一个程序读取文件时,执行后报错信息如下:

          Traceback (most recent call last):

          File "H:/Python培训/3.第三模块/作业/选课系统/bin/course_system.py", line 10, in <module>

          main.run()

          File "H:\Python培训\3.第三模块\作业\选课系统\core\main.py", line 47, in run

         choice_list[choice]()

         File "H:\Python培训\3.第三模块\作业\选课系统\core\main.py", line 10, in admin

         with open("%s/db/admin.json", "r") as f:

         FileNotFoundError: [Errno 2] No such file or directory: '%s/db/admin.json'

       答案:路径中的%s忘记赋值,给%s赋值即可

问题: win 系统下,python3+环境下,写一个程序读取文件时,执行后报错信息如下:

          Traceback (most recent call last):

          File "H:/Python培训/3.第三模块/作业/选课系统/bin/course_system.py", line 10, in <module>

          main.Main.run()

          File "H:\Python培训\3.第三模块\作业\选课系统\core\main.py", line 28, in run

          choice_list[choice]()

          File "H:\Python培训\3.第三模块\作业\选课系统\core\main.py", line 88, in student_login

          student_func.StudentFunc.student_func()

          File "H:\Python培训\3.第三模块\作业\选课系统\core\student_func.py", line 23, in student_func

          choice_list[choice]()

          File "H:\Python培训\3.第三模块\作业\选课系统\core\student_func.py", line 48, in choice_classes

          with open("%s/db/student.text" % base_dir) as f:

           FileNotFoundError: [Errno 2] No such file or directory: 'H:\\Python培训\\3.第三模块\\作业\\选课系统/db/student.text'

          答案:忘记指定文件打开模式,指定打开模式即可

问题: win 系统下,python3+环境下,使用setattr设置一个方法,执行后报错信息如下:

          Traceback (most recent call last):

           2

          File "F:/python/反射.py", line 20, in <module>

         print(d.dog_talk())

        TypeError: talk() missing 2 required positional arguments: 'self' and 'talk'

       答案:dog_talk方法需要传入两个值,其中的self也需要传值,为方法传入对象本身和另外一个值即可。

问题: win 系统下,python3+环境下,写一个服务端程序,执行后报错信息如下:

           Traceback (most recent call last):

           File "H:/Python培训/3.第三模块/2017-11-08/socket_test_server.py", line 12, in <module>

           print("%s连接服务端成功..." % address)

          TypeError: not all arguments converted during string formatting

          答案:conn, address = server.accept()中的address返回的是一个元组,故无法赋值给%s,只要将address中的一个项赋值给%s即可。

问题: win 系统下,python3+环境下,调用一个类的静态方法时,执行后报错信息如下:

          Traceback (most recent call last):

          File "H:/Python培训/3.第三模块/作业/简单FTP_test/FTP_client.py", line 58, in <module>

          ClientFunc.client_func()

          File "H:/Python培训/3.第三模块/作业/简单FTP_test/FTP_client.py", line 18, in client_func

          getattr(ClientFunc, choice_list[choice])()

         TypeError: upload_file() missing 1 required positional argument: 'self'

       答案:静态方法中的self没有去掉,所以需要传值,去掉self即可。

问题: win 系统下,python3+环境下,从服务端下载一个文件时,执行后报错信息如下:

          Traceback (most recent call last):

          File "H:/Python培训/3.第三模块/作业/简单FTP_test/FTP_client.py", line 184, in <module>

          ClientFunc.client_func()

          File "H:/Python培训/3.第三模块/作业/简单FTP_test/FTP_client.py", line 58, in client_func

          getattr(ClientFunc, choice_list[choice])()

          File "H:/Python培训/3.第三模块/作业/简单FTP_test/FTP_client.py", line 106, in download_file

          file_list = pickle.loads(msg) # 打印FTP Server上的文件列表

          _pickle.UnpicklingError: invalid load key, '\xe4'.

         答案:下载的文件已经存在,所以报错。

 

问题: win 系统下,python3+环境下,写一个程序计算字符串的hash值,执行后报错信息如下:

Traceback (most recent call last):

File "H:/Python培训/4.第四模块/作业/高级FTP/FTP_Server/bin/FTP_server.py", line 12, in <module>

main.ServerFunc.run()

File "H:\Python培训\4.第四模块\作业\高级FTP\FTP_Server\core\main.py", line 34, in run

getattr(ServerFunc, choice_list[choice])()

File "H:\Python培训\4.第四模块\作业\高级FTP\FTP_Server\core\main.py", line 18, in run_admin

admin_func.AdminFunc.admin_func()

File "H:\Python培训\4.第四模块\作业\高级FTP\FTP_Server\core\admin_func.py", line 90, in admin_func

go_back = getattr(AdminFunc, choice_list[choice])()

File "H:\Python培训\4.第四模块\作业\高级FTP\FTP_Server\core\admin_func.py", line 22, in add_user

user_info["pw"] = hashlib.sha256(password).hexdigest() # 密码加密并存入字典

TypeError: Unicode-objects must be encoded before hashing

答案:计算hash时传入的必须是byte类型,把字符串encode下即可解决

问题: win 系统下,python3+环境下,写一个程序使用socket发送字典时,执行后报错信息如下:

Exception happened during processing of request from ('127.0.0.1', 56173)

Traceback (most recent call last):

File "C:\Program Files\Python\Python36\lib\socketserver.py", line 639, in process_request_thread

self.finish_request(request, client_address)

File "C:\Program Files\Python\Python36\lib\socketserver.py", line 361, in finish_request

self.RequestHandlerClass(request, client_address, self)

File "C:\Program Files\Python\Python36\lib\socketserver.py", line 696, in __init__

self.handle()

File "H:\Python培训\4.第四模块\作业\高级FTP\FTP_Server\core\server_func.py", line 36, in handle

if self.data["REQ"] == "check_user":

TypeError: byte indices must be integers or slices, not str

答案:socket只能发送byte类型,把字典使用pickle进行序列化后即可发送

问题: win 系统下,python3+环境下,写一个程序使用socket发送字符串时,执行后报错信息如下:

Exception happened during processing of request from ('127.0.0.1', 53055)

Traceback (most recent call last):

用户ccc正在尝试上传文件...

File "C:\Users\MAIMAI\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 639, in process_request_thread

self.finish_request(request, client_address)

File "C:\Users\MAIMAI\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 361, in finish_request

self.RequestHandlerClass(request, client_address, self)

File "C:\Users\MAIMAI\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 696, in __init__

self.handle()

File "F:\python\高级FTP\FTP_Server\core\server_func.py", line 166, in handle

getattr(self, data["REQ"])(data)

File "F:\python\高级FTP\FTP_Server\core\server_func.py", line 84, in put

self.request.sendall("ERROR:磁盘已满!无法上传文件!")

TypeError: a bytes-like object is required, not 'str'

答案:socket只能发送byte类型,把字符串encode下即可解决

问题: win 系统下,python3+环境下,写一个程序使用socket发送数字时,执行后报错信息如下:

Exception happened during processing of request from ('127.0.0.1', 54763)

正在接收文件....

Traceback (most recent call last):

File "C:\Program Files\Python\Python36\lib\socketserver.py", line 639, in process_request_thread

self.finish_request(request, client_address)

File "C:\Program Files\Python\Python36\lib\socketserver.py", line 361, in finish_request

self.RequestHandlerClass(request, client_address, self)

File "C:\Program Files\Python\Python36\lib\socketserver.py", line 696, in __init__

self.handle()

File "H:\Python培训\4.第四模块\作业\高级FTP\FTP_Server\core\server_func.py", line 196, in handle

getattr(self, data["REQ"])(data)

File "H:\Python培训\4.第四模块\作业\高级FTP\FTP_Server\core\server_func.py", line 82, in put

self.receive_file(f, no_extension_name, file_name, file_size, file_md5)

File "H:\Python培训\4.第四模块\作业\高级FTP\FTP_Server\core\server_func.py", line 156, in receive_file

self.request.sendall(size)

TypeError: a bytes-like object is required, not 'int'

答案:socket也无法发送int类型的数字,使用pickle将数字序列化后即可发送

问题: win 系统下,python3+环境下,写一个程序使用paramiko模块通过SSH连接远程主机执行命令时,执行后报错信息如下:

Traceback (most recent call last):

File "H:/Python培训/4.第四模块/2017-11-25/paramiko_test.py", line 10, in <module>

stdout, stderr = ssh.exec_commond("df")

AttributeError: 'SSHClient' object has no attribute 'exec_commond'

答案:调用的方法写错了,ssh.exec_commond改为ssh.exec_command即可

问题: win 系统下,python3+环境下,写一个程序使用paramiko模块通过SSH连接远程主机执行命令时,执行后报错信息如下:

Traceback (most recent call last):

File "F:/python/2017-11-25/paramiko_sshclient_key.py", line 9, in <module>

ssh.connect(hostname="192.168.3.25", port=22, username="fangyu", pkey=rsa_key)

File "C:\Users\MAIMAI\AppData\Local\Programs\Python\Python36\lib\site-packages\paramiko\client.py", line 402, in connect

self, server_hostkey_name, server_key

File "C:\Users\MAIMAI\AppData\Local\Programs\Python\Python36\lib\site-packages\paramiko\client.py", line 768, in missing_host_key

'Server {!r} not found in known_hosts'.format(hostname)

paramiko.ssh_exception.SSHException: Server '192.168.3.25' not found in known_hosts

答案:没有将本机加入远程主机的know_hosts,使用ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())自动将本机加入远程主机的know_hosts即可

问题: win 系统下,python3+环境下,写一个程序启动一个进程时,执行后报错信息如下:

Traceback (most recent call last):

File "F:/python/2017-12-02/进程Manager.py", line 23, in <module>

p.join()

File "C:\Users\MAIMAI\AppData\Local\Programs\Python\Python36\lib\multiprocessing\process.py", line 120, in join

assert self._popen is not None, 'can only join a started process'

AssertionError: can only join a started process

答案:设置好进程之后忘记启动了,使用start()启动进程即可解决

问题: win 系统下,python3+环境下,写一个服务端接受客户端的连接程序,执行后报错信息如下:

Traceback (most recent call last):

File "H:/Python培训/4.第四模块/2017-12-04/select_server.py", line 23, in <module>

print("来自%s的新连接..." % address)

TypeError: not all arguments converted during string formatting

答案:conn, address = server.accept()返回的address为一个元组,取元组的第一项即为IP地址

 

问题: win 系统下,python3+环境下,写一个正则表达式,执行后报错信息如下:

Traceback (most recent call last):

File "H:/Python培训/5.第五模块/作业/主机管理系统(RabbitMQ实现)/HostManage_Client/bin/client.py", line 12, in <module>

main.run()

File "H:\Python培训\5.第五模块\作业\主机管理系统(RabbitMQ实现)\HostManage_Client\core\main.py", line 29, in run

manage.manage_cmd()

File "H:\Python培训\5.第五模块\作业\主机管理系统(RabbitMQ实现)\HostManage_Client\core\manage_func.py", line 61, in manage_cmd

getattr(self, func)(cmd)

File "H:\Python培训\5.第五模块\作业\主机管理系统(RabbitMQ实现)\HostManage_Client\core\manage_func.py", line 14, in run

ip_list = re.findall("\d+.\d+.\d+.\d+")

TypeError: findall() missing 1 required positional argument: 'string'

答案:正则匹配时少了匹配对象,添加上要进行匹配的字符串即可。

问题: win 系统下,python3+环境下,使用pika模块接收RabbitMQ队列中的消息,执行后报错信息如下:

Traceback (most recent call last):

File "H:/Python培训/5.第五模块/2017-12-13/简单rabbitmq_receive.py", line 19, in <module>

channel.basic_consume(callback)

TypeError: basic_consume() missing 1 required positional argument: 'queue'

答案:缺少了queue名参数,添加queue=“队列名”即可。

问题: win 系统下,python3+环境下,使用pika模块接收RabbitMQ队列中的消息,执行后报错信息如下:

Traceback (most recent call last):

File "H:/Python培训/5.第五模块/2017-12-13/简单rabbitmq_receive.py", line 19, in <module>

channel.basic_consume(callback, queue="1")

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\blocking_connection.py", line 1551, in basic_consume

consumer_callback=consumer_callback)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\blocking_connection.py", line 1614, in _basic_consume_impl

self._flush_output(ok_result.is_ready)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\blocking_connection.py", line 1250, in _flush_output

*waiters)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\blocking_connection.py", line 455, in _flush_output

self._impl.ioloop.poll()

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\select_connection.py", line 245, in poll

self._poller.poll()

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\select_connection.py", line 718, in poll

self._dispatch_fd_events(fd_event_map)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\select_connection.py", line 625, in _dispatch_fd_events

handler(fileno, events)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\base_connection.py", line 395, in _handle_events

self._handle_read()

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\base_connection.py", line 449, in _handle_read

self._on_data_available(data)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\connection.py", line 1938, in _on_data_available

self._process_frame(frame_value)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\connection.py", line 2059, in _process_frame

if self._process_callbacks(frame_value):

File "C:\Program Files\Python\Python36\lib\site-packages\pika\connection.py", line 2040, in _process_callbacks

frame_value) # Args

File "C:\Program Files\Python\Python36\lib\site-packages\pika\callback.py", line 60, in wrapper

return function(*tuple(args), **kwargs)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\callback.py", line 92, in wrapper

return function(*args, **kwargs)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\callback.py", line 236, in process

callback(*args, **keywords)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\blocking_connection.py", line 1316, in _on_channel_closed

method.reply_text)

pika.exceptions.ChannelClosed: (404, "NOT_FOUND - no queue '1' in vhost '/'")

答案:使用了一个不存在的queue名,配置正确的queue名即可。

问题: win 系统下,python3+环境下,使用pika模块连接远程主机上的RabbitMQ时,执行后报错信息如下:

Traceback (most recent call last):

File "H:/Python培训/5.第五模块/2017-12-15/rabbitmq_test.py", line 6, in <module>

conn = pika.BlockingConnection(pika.ConnectionParameters("192.168.0.231", 5672, "/", user))

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\blocking_connection.py", line 374, in __init__

self._process_io_for_connection_setup()

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\blocking_connection.py", line 414, in _process_io_for_connection_setup

self._open_error_result.is_ready)

File "C:\Program Files\Python\Python36\lib\site-packages\pika\adapters\blocking_connection.py", line 466, in _flush_output

raise maybe_exception

pika.exceptions.ProbableAuthenticationError: (403, 'ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.')

答案:RabbitMQ默认的guest用户无法用于远程登录,在RabbitMQ中添加一个新用户即可。

问题: win 系统下,python3+环境下,连接远程主机上的Redis时,执行后报错信息如下:

Traceback (most recent call last):

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 484, in connect

sock = self._connect()

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 541, in _connect

raise err

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 529, in _connect

sock.connect(socket_address)

ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "C:\Program Files\Python\Python36\lib\site-packages\redis\client.py", line 667, in execute_command

connection.send_command(*args)

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 610, in send_command

self.send_packed_command(self.pack_command(*args))

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 585, in send_packed_command

self.connect()

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 489, in connect

raise ConnectionError(self._error_message(e))

redis.exceptions.ConnectionError: Error 10061 connecting to 192.168.0.231:6379. 由于目标计算机积极拒绝,无法连接。.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 484, in connect

sock = self._connect()

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 541, in _connect

raise err

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 529, in _connect

sock.connect(socket_address)

ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "H:/Python培训/5.第五模块/2017-12-14/连接redis.py", line 6, in <module>

r.set("a", "aa")

File "C:\Program Files\Python\Python36\lib\site-packages\redis\client.py", line 1171, in set

return self.execute_command('SET', *pieces)

File "C:\Program Files\Python\Python36\lib\site-packages\redis\client.py", line 673, in execute_command

connection.send_command(*args)

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 610, in send_command

self.send_packed_command(self.pack_command(*args))

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 585, in send_packed_command

self.connect()

File "C:\Program Files\Python\Python36\lib\site-packages\redis\connection.py", line 489, in connect

raise ConnectionError(self._error_message(e))

redis.exceptions.ConnectionError: Error 10061 connecting to 192.168.0.231:6379. 由于目标计算机积极拒绝,无法连接。.

答案:Redis默认无法支持远程登录,只能本地登录,修改Reids的配置文件redis.conf中的bind 127.0.0.1为bind 0.0.0.0或你的IP即可。

问题: win 系统下,python3+环境下,使用SQLAlchemy在MySQL中写入数据时,执行后报错信息如下:

Traceback (most recent call last):

File "H:/Python培训/5.第五模块/2018-01-02/orm查询数据.py", line 20, in <module>

data = Session.query(Student).filter_by(name="gougou").first()

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\orm\query.py", line 2778, in first

ret = list(self[0:1])

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\orm\query.py", line 2570, in __getitem__

return list(res)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\orm\query.py", line 2878, in __iter__

return self._execute_and_instances(context)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\orm\query.py", line 2899, in _execute_and_instances

close_with_result=True)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\orm\query.py", line 2908, in _get_bind_args

**kw

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\orm\query.py", line 2890, in _connection_from_session

conn = self.session.connection(**kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\orm\session.py", line 1025, in connection

bind = self.get_bind(mapper, clause=clause, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\orm\session.py", line 1387, in get_bind

', '.join(context)))

sqlalchemy.exc.UnboundExecutionError: Could not locate a bind configured on mapper Mapper|Student|student, SQL expression or this Session

答案:在实例化sessionmaker时忘记bind=engine了。

问题: win 系统下,python3+环境下,使用SQLAlchemy在MySQL中写入数据时,执行后报错信息如下:

Traceback (most recent call last):

File "H:/Python培训/5.第五模块/2018-01-03/orm插入多条记录.py", line 17, in <module>

Base.metadata.create_all()

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\schema.py", line 4000, in create_all

bind = _bind_or_error(self)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\base.py", line 636, in _bind_or_error

raise exc.UnboundExecutionError(msg)

sqlalchemy.exc.UnboundExecutionError: MetaData object is not bound to an Engine or Connection. Execution can not proceed without a database to execute against.

答案:Base.metadata.create_all()忘记加engine,改成Base.metadata.create_all(engine)即可。

问题: win 系统下,python3+环境下,使用SQLAlchemy在MySQL中创建表时,执行后报错信息如下:

Traceback (most recent call last):

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 2444, in visit_create_table

and not first_pk)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 245, in process

return obj._compiler_dispatch(self, **kwargs)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch

return meth(self, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 2475, in visit_create_column

first_pk=first_pk

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\dialects\mysql\base.py", line 1131, in get_column_specification

column.type, type_expression=column)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 293, in process

return type_._compiler_dispatch(self, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch

return meth(self, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 2914, in visit_string

return self.visit_VARCHAR(type_, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\dialects\mysql\base.py", line 1538, in visit_VARCHAR

self.dialect.name)

sqlalchemy.exc.CompileError: VARCHAR requires a length on dialect mysql

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

File "H:/Python培训/5.第五模块/作业/堡垒机/Fortress/bin/fortress.py", line 10, in <module>

from core import main

File "H:\Python培训\5.第五模块\作业\堡垒机\Fortress\core\main.py", line 4, in <module>

from core import tables

File "H:\Python培训\5.第五模块\作业\堡垒机\Fortress\core\tables.py", line 18, in <module>

Base.metadata.create_all(engine)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\schema.py", line 4004, in create_all

tables=tables)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 1940, in _run_visitor

conn._run_visitor(visitorcallable, element, **kwargs)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 1549, in _run_visitor

**kwargs).traverse_single(element)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\visitors.py", line 121, in traverse_single

return meth(obj, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\ddl.py", line 757, in visit_metadata

_is_metadata_operation=True)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\visitors.py", line 121, in traverse_single

return meth(obj, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\ddl.py", line 791, in visit_table

include_foreign_key_constraints=include_foreign_key_constraints

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 948, in execute

return meth(self, multiparams, params)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\ddl.py", line 68, in _execute_on_connection

return connection._execute_ddl(self, multiparams, params)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 1003, in _execute_ddl

if not self.schema_for_object.is_default else None)

File "<string>", line 1, in <lambda>

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\elements.py", line 442, in compile

return self._compiler(dialect, bind=bind, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\ddl.py", line 26, in _compiler

return dialect.ddl_compiler(dialect, self, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 219, in __init__

self.string = self.process(self.statement, **compile_kwargs)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 245, in process

return obj._compiler_dispatch(self, **kwargs)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch

return meth(self, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 2455, in visit_create_table

(table.description, column.name, ce.args[0])

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\util\compat.py", line 203, in raise_from_cause

reraise(type(exception), exception, tb=exc_tb, cause=cause)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\util\compat.py", line 186, in reraise

raise value.with_traceback(tb)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 2444, in visit_create_table

and not first_pk)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 245, in process

return obj._compiler_dispatch(self, **kwargs)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch

return meth(self, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 2475, in visit_create_column

first_pk=first_pk

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\dialects\mysql\base.py", line 1131, in get_column_specification

column.type, type_expression=column)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 293, in process

return type_._compiler_dispatch(self, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch

return meth(self, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\sql\compiler.py", line 2914, in visit_string

return self.visit_VARCHAR(type_, **kw)

File "C:\Program Files\Python\Python36\lib\site-packages\sqlalchemy\dialects\mysql\base.py", line 1538, in visit_VARCHAR

self.dialect.name)

sqlalchemy.exc.CompileError: (in table 'tesetable', column 'name'): VARCHAR requires a length on dialect mysql

答案:表的字符型字段创建时没有指定长度,为该字段指定长度即可。

posted on 2017-09-28 22:17  青蛙二世  阅读(10559)  评论(0编辑  收藏  举报

导航