最近很多小伙伴都在问PythonMySQLdb问题和TypeError:%d格式:需要数字,而不是str这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展Python3TypeErr
最近很多小伙伴都在问Python MySQLdb问题和TypeError:%d格式:需要数字,而不是str这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展Python 3 TypeError:必须为str,而不是sys.stdout.write()的字节、Python JSON TypeError列表索引必须是整数或切片,而不是str、Python MySQLdb TypeError:在字符串格式化期间并非所有参数都已转换、Python SocketServer错误:TypeError:需要一个类似字节的对象,而不是'str'等相关知识,下面开始了哦!
本文目录一览:- Python MySQLdb问题(TypeError:%d格式:需要数字,而不是str)
- Python 3 TypeError:必须为str,而不是sys.stdout.write()的字节
- Python JSON TypeError列表索引必须是整数或切片,而不是str
- Python MySQLdb TypeError:在字符串格式化期间并非所有参数都已转换
- Python SocketServer错误:TypeError:需要一个类似字节的对象,而不是'str'
Python MySQLdb问题(TypeError:%d格式:需要数字,而不是str)
我正在尝试执行以下插入操作:
cursor.execute(""" insert into tree (id,parent_id,level,description,code,start,end) values (%d,%d,%d,%s,%s,%f,%f) """, (1,1,1,''abc'',''def'',1,1) )
我的MYSQL表的结构是:
id int(255),parent_id int(255),level int(11),description varchar(255),code varchar(255),start decimal(25,4),end decimal(25,4)
但是,当我运行程序时,出现错误
执行查询=“%db.literal(args)”中的“ File“
/usr/lib/pymodules/python2.6/MySQLdb/cursors.py”,第151行TypeError:%d格式:必须为数字,而不是str“
答案1
小编典典格式字符串实际上不是普通的Python格式字符串。您必须始终%s
对所有字段使用。
参考官方文件:
如果args是列表或元组,则%s可用作查询中的 占位符 。如果args是字典,则%(name)s可用作查询中的占位符。
- >那就是:这里%s
是 不是格式化 ,但是 是一个占位符
Python 3 TypeError:必须为str,而不是sys.stdout.write()的字节
我一直在寻找一种从python脚本运行外部进程并在执行期间打印其stdout消息的方法。
下面的代码有效,但是在运行时不输出标准输出。退出时,出现以下错误:
sys.stdout.write(nextline)TypeError:必须为str,而不是字节
p = subprocess.Popen(["demo.exe"],stdout = subprocess.PIPE,stderr= subprocess.PIPE)
# Poll process for new output until finished
while True:
nextline = p.stdout.readline()
if nextline == '' and p.poll() != None:
break
sys.stdout.write(nextline)
sys.stdout.flush()
output = p.communicate()[0]
exitCode = p.returncode
我正在使用python 3.3.2
Python JSON TypeError列表索引必须是整数或切片,而不是str
我目前正在尝试从发布请求响应中解析一些数据,并且不断收到此错误:“ TypeError:列表索引必须是整数或切片,而不是str”
Python代码
import requests
import json
count = 0
params = {'var1':'40','value':'143','itm':'1','param':'1'}
req = 'https://www.api.com/api/search'
data = requests.post(req,data = params).json()
print (data['result']['results']['name'])
JSON回应
{
"result":{
"count":1,"totalCount":1,"offset":0,"queryTime":232,"results":[
{
"rating":"4.0","productId":{
"upc":"143","ItemId":"143","productId":"143-prd"
},"name":"Product","catagory":{
"name":"","CataId":1
},"images":{
"thumbnailUrl":"http://api.com/img/static/product-image-50-50.png","largeUrl":"http://api.com/img/static/product-image-500-500.png"
},"price":{
"price":13,"isRealTime":true,"currencyUnit":"USD"
},"location":{
"unit":[],"detailed":[]
},"inventory":{
"quantity":1,"status":"In Stock","isRealTime":true
},"ratings":{
"rating":"3.1875","ratingUrl":"http://api.com/3_1875.gif"
},"reviews":{
"reviewCount":"2"
},"isItem":true,"lUrl":"/l/Product-Name"
}
],"performance":{
"enrichment":{
}
},"query":{
"originalQuery":"143","actualQuery":"143","suggestedQueries":[
]
},"algo":"jarvis","blacklist":false,"cluster":{
"apiserver":{
"hostname":"site.api.com","pluginVersion":"1.0"
},"searchengine":{
"hostname":"srch.site.api.com"
}
}
}
}
我做了类似的代码,但这是一个get请求,一切都很好。
Python MySQLdb TypeError:在字符串格式化期间并非所有参数都已转换
运行此脚本后:
#! /usr/bin/env pythonimport MySQLdb as mdbimport sysclass Test: def check(self, search): try: con = mdb.connect(''localhost'', ''root'', ''password'', ''recordsdb''); cur = con.cursor() cur.execute( "SELECT * FROM records WHERE email LIKE ''%s''", search ) ver = cur.fetchone() print "Output : %s " % ver except mdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) finally: if con: con.close()test = Test()test.check("test")
我收到以下错误:
./lookup Traceback (most recent call last): File "./lookup", line 27, in <module> test.check("test") File "./lookup", line 11, in creep cur.execute( "SELECT * FROM records WHERE email LIKE ''%s''", search ) File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute query = query % tuple([db.literal(item) for item in args])TypeError: not all arguments converted during string formatting
我不知道为什么。我正在尝试进行参数化查询,但这只是痛苦。我是Python的新手,所以这可能是一个明显的问题。
答案1
小编典典代替这个:
cur.execute( "SELECT * FROM records WHERE email LIKE ''%s''", search )
尝试这个:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )
参见MySQLdb文档。原因是execute
的第二个参数表示要转换的对象的列表,因为在参数化查询中可以有任意数量的对象。在这种情况下,您只有一个,但是它仍然需要是可迭代的(用元组代替列表也可以)。
Python SocketServer错误:TypeError:需要一个类似字节的对象,而不是'str'
如何解决Python SocketServer错误:TypeError:需要一个类似字节的对象,而不是''str''?
我正在制作Growtopia服务器仿真器 (出于教育目的:我将对其进行测试,并可能在将来制造专用服务器。希望我能做到) 奇怪的是我刚收到此错误,我正在使用堆栈溢出修复该死的错误,谢谢大家……
这是我的代码:
import http.server
import socketserver
class ServerHandler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(200)
self.end_headers()
self.wfile.write("server|127.0.0.1\nport|17091\ntype|1\n#maint|Server is not available!\n\nbeta_server|127.0.0.1\nbeta_port|17091\n\nbeta_type|1\nMeta|localhost\nRTENDMARKERBS1001")
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write("server|127.0.0.1\nport|17091\ntype|1\n#maint|Server is not available!\n\nbeta_server|127.0.0.1\nbeta_port|17091\n\nbeta_type|1\nMeta|localhost\nRTENDMARKERBS1001")
def log_message(self,format,*args):
return
Handler = http.server.SimpleHTTPRequestHandler
PORT = 80
HOST = ""
OUT_HOST = HOST
info = OUT_HOST,PORT
httpd = socketserver.Tcpserver((HOST,PORT),ServerHandler)
print("Server Port : ",PORT)
if "" in (OUT_HOST):
print("Server Hostname : ","localhost")
else:
print("Server Hostname : ",HOST)
httpd.serve_forever()
这是Stacktrace:
Exception happened during processing of request from (''127.0.0.1'',52331)
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\python38-32\lib\socketserver.py",line 316,in _handle_request_noblock
self.process_request(request,client_address)
File "C:\Users\HP\AppData\Local\Programs\Python\python38-32\lib\socketserver.py",line 347,in process_request
self.finish_request(request,line 360,in finish_request
self.RequestHandlerClass(request,client_address,self)
File "C:\Users\HP\AppData\Local\Programs\Python\python38-32\lib\socketserver.py",line 720,in __init__
self.handle()
File "C:\Users\HP\AppData\Local\Programs\Python\python38-32\lib\http\server.py",line 427,in handle
self.handle_one_request()
File "C:\Users\HP\AppData\Local\Programs\Python\python38-32\lib\http\server.py",line 415,in handle_one_request
method()
File "C:/Users/HP/PycharmProjects/Crescentstar/main.py",line 10,in do_POST
self.wfile.write("server|127.0.0.1\nport|17091\ntype|1\n#maint|Server is not available!\n\nbeta_server|127.0.0.1\nbeta_port|17091\n\nbeta_type|1\nMeta|localhost\nRTENDMARKERBS1001").encode()
File "C:\Users\HP\AppData\Local\Programs\Python\python38-32\lib\socketserver.py",line 799,in write
self._sock.sendall(b)
TypeError: a bytes-like object is required,not ''str''
解决方法
根据所提供的没有堆栈跟踪的信息,我相信您可能应该向wfile.write提供字节而不是字符串。
在要编写的字符串的末尾添加.encode(),或在其前面加上b。
关于Python MySQLdb问题和TypeError:%d格式:需要数字,而不是str的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Python 3 TypeError:必须为str,而不是sys.stdout.write()的字节、Python JSON TypeError列表索引必须是整数或切片,而不是str、Python MySQLdb TypeError:在字符串格式化期间并非所有参数都已转换、Python SocketServer错误:TypeError:需要一个类似字节的对象,而不是'str'等相关知识的信息别忘了在本站进行查找喔。
本文标签: