python print IOError

遇到个问题,linux下使用python 2.7的print 偶尔会报错:IOError :(5,'Input/output error').
出现的几率很小,现在还没找到原因.求有经验的大神指点.

1个回答

起码要看看一下,出错的时候,打印的内容等。5 是不是当时访问IO设备

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
python 爬虫 出现IOError错误
# -*- coding:utf-8 -*- #! /usr/bin/env python import urllib import urllib2 import re page = 1 url = 'http://www.qiushibaike.com/hot/page/' + str(page) user_agent = 'Mozilla/4.0(compatible;MSIE 5.5;Windows NT)' headers = {'User-Agent':user_agent} try: request = urllib2.Request(url,headers = headers) response = urllib2.urlopen(request) content = response.read().decode('utf-8','ignore') pattern = re.compile(r'<div.*?author.*?>*?<img.*?>.*?<a.*?title="(.*?)">.*?<div.*?>.*?(.*?)</div>', re.S) items = re.findall(pattern,content) for item in items: print item[0],item[1] except urllib2.URLError, e: if hasattr(e,"code"): print e.code if hasattr(e,"reason"): print e.reason ```![图片说明](https://img-ask.csdn.net/upload/201604/29/1461898513_494366.png) ```这是出现错误的信息,在powershell中设置chcp 65001就会出现IOError错误,设置成chcp 437或者936就会出现下面的乱码,请问是什么原因? ``` ```
python下载图片出现IOError
``` import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen('http://bbs.hupu.com/13608969.html') contents = page.read() soup = BeautifulSoup(contents) img=soup.findAll('img') print img print len(img) for myimg in img: link=myimg.get('src') print link content2 = urllib2.urlopen(link).read() with open(u'E:\img'+'/'+link[-11:],'wb') as code: code.write(content2) ``` 能下载两张图,然后出现下面的错误 ![图片说明](https://img-ask.csdn.net/upload/201509/02/1441203328_483250.png) 求高手解决
python爬虫爬取图片和图片的标题保存时出现IOError
import urllib import urllib2 import re import os #爬取索引页面源代码 siteURL='https://www.warningsignsdirect.co.uk/index.php?cPath=518' request=urllib2.Request(siteURL) response=urllib2.urlopen(request) page=response.read().decode('utf-8') print u"已爬取索引页面源代码" os.chdir("C:\Users\hey_fall\Desktop") #抓取页面中指定的图片 pattern=re.compile('<td align="center" class="smallText" width="33%" valign="middle"><a href=".*?"><img src=".*?" alt=".*?" title=".*?" .*? /><br><br>.*?</a><br><br><br><br></td>',re.S) content=re.findall(pattern,page) patternImg=re.compile('<img src="(.*?)"',re.S) images=re.findall(patternImg,str(content)) print u"已爬取该网页图片" #抓取图片的说明文本 patternIntroductions=re.compile('title="(.*?)"',re.S) Introductions=re.findall(patternIntroductions,str(content)) #去除匹配字符中的转义字符 number=0 for introduction in Introductions: Introductions[number]=str(introduction).replace('\\','') number+=1 print u"已爬取图片的说明文本" #抓取说明文本的标题 patternTitle=re.compile('<title>(.*?) </title>') Title=re.findall(patternTitle,page) print u"已爬取文本标题" #创建文件夹 path=os.getcwd() title=Title[0] new_path=os.path.join(path,title) if not os.path.isdir(new_path): os.makedirs(new_path) os.chdir(new_path) print u"已创建文件夹",new_path #保存图片的说明文本 IntroductionName=Title[0]+".txt" f=open(IntroductionName,'w+') for introduction in Introductions: f.write(introduction+'\n') f.close() print u"图片的说明文本已保存到",new_path #保存抓取到的图片 number=0 for imageURL in images: filename=Introductions[number]+'.jpg' url='https://www.warningsignsdirect.co.uk'+'/'+imageURL urllib.urlretrieve(url,filename) number+=1 print u"图片已保存到",new_path print u"该网页内容爬取完毕"
ubuntu上python无法爬取网页
在ubuntu12.04下写了个简单的python测试代码: # -*- coding: UTF-8 -*- import time,urllib2,urllib,StringIO,sys,os,multiprocessing,sqlite3 if __name__ == '__main__': stockUrl="http://www.baidu.com" stockWeb = urllib.urlopen(stockUrl).read() print stockWeb 但是出现了如下错误: Traceback (most recent call last): File "test.py", line 6, in <module> stockWeb = urllib.urlopen(stockUrl).read() File "/usr/lib/python2.7/urllib.py", line 86, in urlopen return opener.open(url) File "/usr/lib/python2.7/urllib.py", line 207, in open return getattr(self, name)(url) File "/usr/lib/python2.7/urllib.py", line 344, in open_http h.endheaders(data) File "/usr/lib/python2.7/httplib.py", line 954, in endheaders self._send_output(message_body) File "/usr/lib/python2.7/httplib.py", line 814, in _send_output self.send(msg) File "/usr/lib/python2.7/httplib.py", line 776, in send self.connect() File "/usr/lib/python2.7/httplib.py", line 757, in connect self.timeout, self.source_address) File "/usr/lib/python2.7/socket.py", line 553, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): IOError: [Errno socket error] [Errno -2] Name or service not known GOOGLE了也没找到解决办法,这是什么问题? 另外,同样的代码吗,我在另一台同样环境机器上是可以运行的
python简单读写文件问题代码纠错
def write(self,fname): import os ls = os.linesep while True: if os.path.exists(fname): print "ERROR:'%s'already exists"%fname break else: break all=[] print"\nEnter lines('.'by itself to quit).\n" while True: entry=raw_input('>') if entry=='.': break else: all.append(entry) fobj=open(fname,'w') fobj.writelines(['%s%s'%(x,ls)for x in all]) fobj.close() print 'DONE!' def read(self,fname): print try: fobj=open(fname,'r') except IOError,e: print"***file open error:",e else: for eachline in fobj: print eachline fobj.close() import os way=raw_input("choose you want to do Write or Read:") if way==Write: write() elif way==Read: read() else:print 'ERROR'
python HTMLParser问题
在看python核心编程第三版的时候遇到的问题 ```import io import formatter from html.parser import HTMLParser import http import os import sys import urllib.request from urllib.parse import urlparse,urljoin class Retriever(object): __slots__=('url','file') def __init__(self,url): self.url,self.file=self.get_file(url) def get_file(self,url,default='index.html'): 'Create usable local filename from URL' parsed=urlparse(url) host=parsed.netloc.split('@')[-1].split(':')[0] filepath='%s%s' % (host,parsed.path) if not os.path.splitext(parsed.path)[1]: filepath=os.path.join(filepath,default) linkdir=os.path.dirname(filepath) if not os.path.isdir(linkdir): if os.path.exists(linkdir): os.unlink(linkdir) os.makedirs(linkdir) return url,filepath def download(self): 'Download URL to specific named file' try: retval=urllib.request.urlretrieve(self.url,self.file) except (IOError,httplib.InvalidURL) as e: retval=(('*** ERROR: bad URL "%s": %s' % (self.url, e)),) return retval def parse_links(self): 'Parse out the links found in download HTML file' f=open(self.file,'rb') data=f.read() f.close() parser=HTMLParser(formatter.AbstractFormatter(formatter.DumbWriter(io.StringIO()))) parser.feed(data) parser.close() return parser.anchorlist class Crawler(object): count=0 def __init__(self, url): self.q=[url] self.seen=set() parsed=urlparse(url) host=parsed.netloc.split('@')[-1].split(':')[0] self.dom='.'.join(host.split('.')[-2:]) def get_page(self, url, media=False): 'Download page & parse links, add to queue if nec' r=Retriever(url) fname=r.download()[0] if fname[0] == '*': print(fname,'...skipping parse') return Crawler.count += 1 print('\n(',Crawler.count,')') print('URL:',url) print('FILE:',fname) self.seen.add(url) ftype=os.path.splitext(fname)[1] if ftype not in ('.htm', '.html'): return for link in r.parse_links(): if link.startswith('mailto:'): print('...discarded, mailto link') continue if not media: ftype=os.path.splitext(link)[1] if ftype in ('.mp3', '.mp4', '.m4v', '.wav'): print('...discarded, media file') continue if not link.startswith('http://'): link=urljoin(url,link) print('*',link) if link not in self.seen: if self.dom not in link: print('...discarded, not in domain') else: if link not in self.q: self.q.append(link) print('...new, added to Q') else: print('...discarded, already in Q') else: print('...discarded, already processed') def go(self,media=False): 'Process next page in queue (if any)' while self.q: url=self.q.pop() self.get_page(url,media) def main(): if len(sys.argv) > 1: url=sys.argv[1] else: try: url=input('Enter starting URL: ') except (KeyboardInterrupt, EOFError): url='' if not url: return if not url.startswith('http://') and not url.startswith('ftp://'): url='http://%s/' % url robot=Crawler(url) robot.go() if __name__=='__main__': main() ``` 这里报错HTMLParser的__init__()需要一个位置参数而给了它两个 看了下文档,好像这个类只有一个关键字参数,给的例子也是先自定义一个子类再实例化,那么书上这么写是什么意思?要怎么改?求解答
python截屏问题 win32和PIL
服务器部署截屏程序,本地远程登录服务器的时候能正常截屏,如果把远程界面关闭或者最小化的时候,截屏就会失败 使用PIL的情况: ``` coordinate = (0, 0, 60,20) pic = ImageGrab.grab(coordinate) ``` 错误信息: ``` File "E:\python-workspace\crawler-20150529\spiders\gz_spider.py", line 141, in _do_crawl_img_by_screenshot pic = ImageGrab.grab(coordinate) # 截图 File "D:\Python27\lib\site-packages\PIL\ImageGrab.py", line 34, in grab size, data = grabber() IOError: screen grab failed ``` 使用win32截屏也是用户界面打开的时候能成功,把远程界面退出或者最小化的时候截屏失败,代码如下: ``` GrabUtil.py def grab(dpath,args): ''''' 参数为指定保存的目录 返回图片文件名,文件名格式:日期.jpg 如:2009328224853.jpg ''' hwnd = 0 hwndDC = win32gui.GetWindowDC(hwnd) mfcDC=win32ui.CreateDCFromHandle(hwndDC) saveDC=mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() MoniterDev=win32api.EnumDisplayMonitors(None,None) #w = MoniterDev[0][2][2] #h = MoniterDev[0][2][3] w = args[2] h = args[3] #print w,h   #图片大小 saveBitMap.CreateCompatibleBitmap(mfcDC, w,h) saveDC.SelectObject(saveBitMap) saveDC.BitBlt((0,0),(w, h) , mfcDC, (args[0],args[1]), win32con.SRCCOPY) cc=time.gmtime() bmpname=str(cc[0])+str(cc[1])+str(cc[2])+str(cc[3]+8)+str(cc[4])+str(cc[5])+'.bmp' saveBitMap.SaveBitmapFile(saveDC, bmpname) pic = Image.open(bmpname) pic.save(os.path.join(dpath, 'xxxxx.jpeg'), 'jpeg') os.remove(bmpname) return pic ``` 报错信息: ``` File "E:\python-workspace\crawler-20150529\spiders\sele.py", line 162, in _do_crawl_img img = self._do_crawl_img_by_screenshot() File "E:\python-workspace\crawler-20150529\spiders\sz_spider.py", line 149, in _do_crawl_img_by_screenshot pic = grab(self.storage_path,coordinate) File "E:\python-workspace\crawler-20150529\GrabUtil.py", line 24, in grab saveDC.BitBlt((0,0),(w, h) , mfcDC, (args[0],args[1]), win32con.SRCCOPY) error: BitBlt failed ``` 初步判定原因:win7 服务器用户登录的时候截屏没有问题,本地远程登陆这台服务器的时候也没有问题,远程界面最小化的时候界面可能调用的是本地服务器的本地方法截屏,所以失败,当我关闭远程界面的时候,这个时候服务器是没有用户登录的状态,所以截屏也失败了,希望那位大牛能帮忙解决问题,告知具体原因
【求助】Python新手上路,报错令人头大!
# OpenCV的库,如下是代码 ``` import os import sys import cv2 import numpy as np def normalize(X, low, high, dtype=None): """Normalizes a given array in X to a value between low and high.""" X = np.asarray(X) minX, maxX = np.min(X), np.max(X) # normalize to [0...1]. X = X - float(minX) X = X / float((maxX - minX)) # scale to [low...high]. X = X * (high-low) X = X + low if dtype is None: return np.asarray(X) return np.asarray(X, dtype=dtype) def read_images(path, sz=None): """Reads the images in a given folder, resizes images on the fly if size is given. Args: path: Path to a folder with subfolders representing the subjects (persons). sz: A tuple with the size Resizes Returns: A list [X,y] X: The images, which is a Python list of numpy arrays. y: The corresponding labels (the unique number of the subject, person) in a Python list. """ c = 0 X,y = [], [] for dirname, dirnames, filenames in os.walk(path): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) for filename in os.listdir(subject_path): try: if (filename == ".directory"): continue filepath = os.path.join(subject_path, filename) im = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE) if (im is None): print ("image " + filepath + " is none") else: print (filepath) # resize to given size (if given) if (sz is not None): im = cv2.resize(im, (200, 200)) X.append(np.asarray(im, dtype=np.uint8)) y.append(c) except IOError as (errno, strerror): print ("I/O error({0}): {1}".format(errno, strerror)) except: print ("Unexpected error:", sys.exc_info()[0]) raise print (c) c = c+1 print (y) return [X,y] def face_rec(): names = ['Gaving', 'Mengxing', 'Cookie'] if len(sys.argv) < 2: print ("USAGE: facerec_demo.py </path/to/images> [</path/to/store/images/at>]") sys.exit() [X,y] = read_images(sys.argv[1]) y = np.asarray(y, dtype=np.int32) if len(sys.argv) == 3: out_dir = sys.argv[2] model = cv2.face.createEigenFaceRecognizer() model.train(np.asarray(X), np.asarray(y)) camera = cv2.VideoCapture(0) face_cascade = cv2.CascadeClassifier('E:\\OPCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml') while (True): read, img = camera.read() faces = face_cascade.detectMultiScale(img, 1.3, 5) for (x, y, w, h) in faces: img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) roi = gray[x:x+w, y:y+h] try: roi = cv2.resize(roi, (200, 200), interpolation=cv2.INTER_LINEAR) print (roi.shape) params = model.predict(roi) print ("Label: %s, Confidence: %.2f" % (params[0], params[1])) cv2.putText(img, names[params[0]], (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2) if (params[0] == 0): cv2.imwrite('face_rec.jpg', img) except: continue cv2.imshow("camera", img) if cv2.waitKey(1000 / 12) & 0xff == ord("q"): break cv2.destroyAllWindows() if __name__ == "__main__": face_rec() def original(): # This is where we write the images, if an output_dir is given # in command line: out_dir = None names = ['Gaving', 'Mengxing', 'Cookie'] # You'll need at least a path to your image data, please see # the tutorial coming with this source code on how to prepare # your image data: if len(sys.argv) < 2: print ("USAGE: facerec_demo.py </path/to/images> [</path/to/store/images/at>]") sys.exit() # Now read in the image data. This must be a valid path! [X,y] = read_images(sys.argv[1]) # Convert labels to 32bit integers. This is a workaround for 64bit machines, # because the labels will truncated else. This will be fixed in code as # soon as possible, so Python users don't need to know about this. # Thanks to Leo Dirac for reporting: y = np.asarray(y, dtype=np.int32) # If a out_dir is given, set it: if len(sys.argv) == 3: out_dir = sys.argv[2] # Create the Eigenfaces model. We are going to use the default # parameters for this simple example, please read the documentation # for thresholding: #model = cv2.face.createLBPHFaceRecognizer() model = cv2.face.createEigenFaceRecognizer() # Read # Learn the model. Remember our function returns Python lists, # so we use np.asarray to turn them into NumPy lists to make # the OpenCV wrapper happy: model.train(np.asarray(X), np.asarray(y)) # We now get a prediction from the model! In reality you # should always use unseen images for testing your model. # But so many people were confused, when I sliced an image # off in the C++ version, so I am just using an image we # have trained with. # # model.predict is going to return the predicted label and # the associated confidence: camera = cv2.VideoCapture(0) face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml') while (True): read, img = camera.read() faces = face_cascade.detectMultiScale(img, 1.3, 5) for (x, y, w, h) in faces: img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) roi = gray[x:x+w, y:y+h] roi = cv2.resize(roi, (200, 200), interpolation=cv2.INTER_LINEAR) print (roi.shape) params = model.predict(roi) print ("Label: %s, Confidence: %.2f" % (params[0], params[1])) cv2.putText(img, names[params[0]], (x,y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 3) cv2.imshow("camera", img) if cv2.waitKey(1000 / 12) & 0xff == ord("q"): break [p_label, p_confidence] = model.predict(np.asarray(X[0])) # Print it: print ("Predicted label = %d (confidence=%.2f)" % (p_label, p_confidence)) # Cool! Finally we'll plot the Eigenfaces, because that's # what most people read in the papers are keen to see. # # Just like in C++ you have access to all model internal # data, because the cv::FaceRecognizer is a cv::Algorithm. # # You can see the available parameters with getParams(): print (model.getParams()) # Now let's get some data: mean = model.getMat("mean") eigenvectors = model.getMat("eigenvectors") # We'll save the mean, by first normalizing it: mean_norm = normalize(mean, 0, 255, dtype=np.uint8) mean_resized = mean_norm.reshape(X[0].shape) if out_dir is None: cv2.imshow("mean", mean_resized) else: cv2.imwrite("%s/mean.png" % (out_dir), mean_resized) # Turn the first (at most) 16 eigenvectors into grayscale # images. You could also use cv::normalize here, but sticking # to NumPy is much easier for now. # Note: eigenvectors are stored by column: for i in xrange(min(len(X), 16)): eigenvector_i = eigenvectors[:,i].reshape(X[0].shape) eigenvector_i_norm = normalize(eigenvector_i, 0, 255, dtype=np.uint8) # Show or save the images: if out_dir is None: cv2.imshow("%s/eigenface_%d" % (out_dir,i), eigenvector_i_norm) else: cv2.imwrite("%s/eigenface_%d.png" % (out_dir,i), eigenvector_i_norm) # Show the images: if out_dir is None: cv2.waitKey(0) cv2.destroyAllWindows() ``` [图片说明](https://img-ask.csdn.net/upload/201904/23/1555987806_94322.jpg) 一直报错,第一次发帖求助,希望大佬不吝赐教!
opencv+python人脸识别问题!请求大佬帮帮忙!
定义 def read_images(path, sz=None): 前是否需要给path赋上路径? (path = 'E:\PyCharm\rebook\data\at' def read_images(path, sz=None):) 还有这样报错,语法哪里出问题? ( File "E:/PyCharm/rebook/4load_pic.py", line 91 except IOError as (errno, strerror): ^ SyntaxError: invalid syntax ) 实在是没办法呀! 各路神仙帮帮忙! ``` import os import sys import cv2 import numpy as np def normalize(X, low, high, dtype=None): """Normalizes a given array in X to a value between low and high.""" X = np.asarray(X) minX, maxX = np.min(X), np.max(X) # normalize to [0...1]. X = X - float(minX) X = X / float((maxX - minX)) # scale to [low...high]. X = X * (high-low) X = X + low if dtype is None: return np.asarray(X) return np.asarray(X, dtype=dtype) path = 'E:\PyCharm\rebook\data\at' def read_images(path, sz=None): """Reads the images in a given folder, resizes images on the fly if size is given. Args: path: Path to a folder with subfolders representing the subjects (persons). sz: A tuple with the size Resizes Returns: A list [X,y] X: The images, which is a Python list of numpy arrays. y: The corresponding labels (the unique number of the subject, person) in a Python list. """ c = 0 X,y = [], [] for dirname, dirnames, filenames in os.walk(path): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) for filename in os.listdir(subject_path): try: if (filename == ".directory"): continue filepath = os.path.join(subject_path, filename) im = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE) if (im is None): print ("image " + filepath + " is none") # resize to given size (if given) if (sz is not None): im = cv2.resize(im, sz) X.append(np.asarray(im, dtype=np.uint8)) y.append(c) except IOError as (errno, strerror): print ("I/O error({0}): {1}".format(errno, strerror)) except: print ("Unexpected error:", sys.exc_info()[0]) raise c = c+1 return [X,y] if __name__ == "__main__": # This is where we write the images, if an output_dir is given # in command line: out_dir = None # You'll need at least a path to your image data, please see # the tutorial coming with this source code on how to prepare # your image data: if len(sys.argv) < 2: print ("USAGE: facerec_demo.py </path/to/images> [</path/to/store/images/at>]") sys.exit() # Now read in the image data. This must be a valid path! [X,y] = read_images(sys.argv[1]) # Convert labels to 32bit integers. This is a workaround for 64bit machines, # because the labels will truncated else. This will be fixed in code as # soon as possible, so Python users don't need to know about this. # Thanks to Leo Dirac for reporting: y = np.asarray(y, dtype=np.int32) # If a out_dir is given, set it: if len(sys.argv) == 3: out_dir = sys.argv[2] # Create the Eigenfaces model. We are going to use the default # parameters for this simple example, please read the documentation # for thresholding: model = cv2.face.createEigenFaceRecognizer() # Read # Learn the model. Remember our function returns Python lists, # so we use np.asarray to turn them into NumPy lists to make # the OpenCV wrapper happy: model.train(np.asarray(X), np.asarray(y)) # We now get a prediction from the model! In reality you # should always use unseen images for testing your model. # But so many people were confused, when I sliced an image # off in the C++ version, so I am just using an image we # have trained with. # # model.predict is going to return the predicted label and # the associated confidence: [p_label, p_confidence] = model.predict(np.asarray(X[0])) # Print it: print ("Predicted label = %d (confidence=%.2f)" % (p_label, p_confidence)) # Cool! Finally we'll plot the Eigenfaces, because that's # what most people read in the papers are keen to see. # # Just like in C++ you have access to all model internal # data, because the cv::FaceRecognizer is a cv::Algorithm. # # You can see the available parameters with getParams(): print (model.getParams()) # Now let's get some data: mean = model.getMat("mean") eigenvectors = model.getMat("eigenvectors") # We'll save the mean, by first normalizing it: mean_norm = normalize(mean, 0, 255, dtype=np.uint8) mean_resized = mean_norm.reshape(X[0].shape) if out_dir is None: cv2.imshow("mean", mean_resized) else: cv2.imwrite("%s/mean.png" % (out_dir), mean_resized) # Turn the first (at most) 16 eigenvectors into grayscale # images. You could also use cv::normalize here, but sticking # to NumPy is much easier for now. # Note: eigenvectors are stored by column: for i in xrange(min(len(X), 16)): eigenvector_i = eigenvectors[:,i].reshape(X[0].shape) eigenvector_i_norm = normalize(eigenvector_i, 0, 255, dtype=np.uint8) # Show or save the images: if out_dir is None: cv2.imshow("%s/eigenface_%d" % (out_dir,i), eigenvector_i_norm) else: cv2.imwrite("%s/eigenface_%d.png" % (out_dir,i), eigenvector_i_norm) # Show the images: if out_dir is None: cv2.waitKey(0) ```
python中sys.argv[1:]到底是什么意思呢?
1 import sys 2 import Image 3 4 for infile in sys.argv[1:]: 5 try: 6 im = Image.open(infile) 7 print infile, im.format, "%dx%d" % im.size, im.mode 8 except IOError: 9 pass 大神们,请问for infile in sys.argv[1:]到底是什么意思呢?新手,请解答简单明了一些,您的回答能帮助我解决燃眉之急!!在此非常之感谢!
继承python内置的list,在创建实例时,提示参数个数不正确
def sanitize(time_string): if "-" in time_string: splitter = "_" elif ":" in time_string: splitter = ":" else: return time_string (mins, secs) = time_string.strip().split(splitter) return mins, ".", secs class AthleteList(list): def __int__(self, a_name, a_dob=None, a_times=[]): list.__init__([]) self.name = a_name self.dob = a_dob self.extend(a_times) def top3(self): return sorted(set([sanitize(t) for t in self]))[0:3] def get_coach_data(filename): try: with open(filename) as f: data = f.readline() templ = data.strip().split(",") return AthleteList([templ.pop(0), templ.pop(0), templ]) except IOError as ioerr: print "File error: ", str(ioerr) return None sarah = get_coach_data("sarah2.txt") print sarah.name, "'s fastest times are: ", str(sarah.top3()) 错误提示: Traceback (most recent call last): File "C:\Python27\listclass2.py", line 30, in <module> sarah = get_coach_data("sarah2.txt") File "C:\Python27\listclass2.py", line 25, in get_coach_data return AthleteList(templ.pop(0), templ.pop(0), templ) TypeError: list() takes at most 1 argument (3 given) 不知道怎么改。。
Python中 "==" 和 控制台输入字符串的问题。
问题1: 我用的是Python2.6 有这个一个程序, 输入文件名, 先是检查文件名, 文件名不存在,则对文件输入内容。 我指定输入'.'的时候停止输入, 但是程序运行过程中,即使输入了'.'循环也不会break掉。 为什么? 代码如下: [code="python"] import os ls = os.linesep fname = raw_input('Enter a file name : ') while True : if os.path.exists(fname) : print "Error : '%s' already exists" %fname else : break all = [] print "\nEnter lines ('.' by itself to quit).\n" while True : entry = raw_input('>') print type(entry) if entry == '.' : #如果输入的字符 == '.' break。但没有实现。 break else : all.append(entry) fobj = open(fname, 'w') fobj.writelines(['%s%s' %(x, ls) for x in all]) fobj.close() print 'DONE!' [/code] 问题2: 在准备读文件内容的时候, 好像输入的文件名有点误会。 在异常信息中,我们看到: Enter filename : data.txt *** file open error : [Errno 22] invalid mode ('r') or filename: '[color=red]data.txt\r[/color]' 这个文件名后面加了 \r 。难道是因为我在控制台输入完文件名后按了 回车 的原因?? 代码如下: [code="python"] fname = raw_input('Enter filename : ') print try : fobj = open(fname, 'r') except IOError, e: print "*** file open error : ", e #这里输出异常,异常信息里filename : data.txt\r else : for eachLine in fobj: print eachLine, fobj.close() [/code] 谢谢大家! [b]问题补充:[/b] 非常感谢 RednaxelaFX 的回答。 补充: 1.我用的windows XP。 用的是 Eclipse3.2 + Pydev。 输入的'.'和'.'用 "==" 就是不等。 2.用str.strip()确实可以得到我想要的filename, 但现在我想知道的是,为什么filename会变成data.txt\r。 难道真的就是因为我在控制台输入了一个 回车, 把回车符号也加进去了 ????
如何用Python 3遍历循环下载CSV文件中内容链接的图片?
## 本人目前情况如下: 现在有个文件表(CSV),表中信息均为图片链接,如图1所示 ![图1](https://img-ask.csdn.net/upload/201811/07/1541602716_663499.png) 很明显,这里需要用到循环,因此我的代码如下: ``` import csv #加载csv包便于读取csv文件 import requests with open ('vehicles.csv','r',encoding = 'utf-8') as csvfile: reader = csv.reader(csvfile) links = [row[1] for row in reader] for link in links: imgresponse = requests.get(link, stream=True) #以流的方式打开 image = imgresponse.content address="H:\程序语言学习用文件夹\Python\images"+"\\" #保存地址 i = 1 try: with open(address+"{0}".format(i) ,"wb") as jpg: jpg.write(image) i = i + 1 except IOError: print("IO Error\n") finally: jpg.close ``` 然而实际情况是,控制台没有报错,但图片只下载了一张,就是最后一张,而且它还被命名成了“1”??!! ## 求助各位大佬,我的代码到底哪里出了不妥?
tensorflow上的一个案例mnist,运行出错,求问
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf # Import data mnist = input_data.read_data_sets('MNIST_data/', one_hot=True) # Create the model x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.matmul(x, W) + b # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, 10]) # The raw formulation of cross-entropy, # # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)), # reduction_indices=[1])) # # can be numerically unstable. # # So here we use tf.nn.softmax_cross_entropy_with_logits on the raw # outputs of 'y', and then average across the batch. cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Train for _ in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Test trained model correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) 错误如下: Traceback (most recent call last): File "/home/linbinghui/文档/pycode/Text-1.py", line 5, in <module> mnist = input_data.read_data_sets('MNIST_data/', one_hot=True) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 189, in read_data_sets local_file = maybe_download(TEST_IMAGES, train_dir, SOURCE_URL + TEST_IMAGES) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 81, in m aybe_download urllib.request.urlretrieve(source_url, temp_file_name) File "/usr/lib/python2.7/urllib.py", line 98, in urlretrieve return opener.retrieve(url, filename, reporthook, data) File "/usr/lib/python2.7/urllib.py", line 245, in retrieve fp = self.open(url, data) File "/usr/lib/python2.7/urllib.py", line 213, in open return getattr(self, name)(url) File "/usr/lib/python2.7/urllib.py", line 364, in open_http return self.http_error(url, fp, errcode, errmsg, headers) File "/usr/lib/python2.7/urllib.py", line 377, in http_error result = method(url, fp, errcode, errmsg, headers) File "/usr/lib/python2.7/urllib.py", line 642, in http_error_302 headers, data) File "/usr/lib/python2.7/urllib.py", line 669, in redirect_internal return self.open(newurl) File "/usr/lib/python2.7/urllib.py", line 213, in open return getattr(self, name)(url) File "/usr/lib/python2.7/urllib.py", line 350, in open_http h.endheaders(data) File "/usr/lib/python2.7/httplib.py", line 1053, in endheaders self._send_output(message_body) File "/usr/lib/python2.7/httplib.py", line 897, in _send_output self.send(msg) File "/usr/lib/python2.7/httplib.py", line 859, in send self.connect() File "/usr/lib/python2.7/httplib.py", line 836, in connect self.timeout, self.source_address) File "/usr/lib/python2.7/socket.py", line 575, in create_connection raise err IOError: [Errno socket error] [Errno 111] Connection refused
unittest测试时,testsuite只能执行第一个用例,单独的用例都可以执行,这是为什么
代码为: class Count: def __init__(self,a,b): self.a = int(a) self.b = int(b) def add(self): return self.a + self.b from calculator import Count import unittest class TestCount(unittest.TestCase): def setUp(self): print('test start') def test_add(self): j = Count(2,3) self.assertEqual(j.add(),5) def test_add2(self): j = Count(41,76) self.assertEqual(j.add(),117) def tearDown(self): print('test end') if __name__ == "__main__": suite = unittest.TestSuite() suite.addTest(TestCount('test_add2')) suite.addTest(TestCount('test_add')) runner = unittest.TextTestRunner() runner.run(suite) 错误为: Traceback (most recent call last): File "<ipython-input-6-e4fc42a6bc0e>", line 1, in <module> runfile('E:/python-workspace/zidonghua/unittest/testsuite_texttestrunner_calculator.py', wdir='E:/python-workspace/zidonghua/unittest') File "C:\Users\liushu\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile execfile(filename, namespace) File "C:\Users\liushu\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "E:/python-workspace/zidonghua/unittest/testsuite_texttestrunner_calculator.py", line 34, in <module> runner.run(suite) File "C:\Users\liushu\Anaconda2\lib\unittest\runner.py", line 151, in run test(result) File "C:\Users\liushu\Anaconda2\lib\unittest\suite.py", line 70, in __call__ return self.run(*args, **kwds) File "C:\Users\liushu\Anaconda2\lib\unittest\suite.py", line 108, in run test(result) File "C:\Users\liushu\Anaconda2\lib\unittest\case.py", line 393, in __call__ return self.run(*args, **kwds) File "C:\Users\liushu\Anaconda2\lib\unittest\case.py", line 368, in run result.addSuccess(self) File "C:\Users\liushu\Anaconda2\lib\unittest\runner.py", line 63, in addSuccess self.stream.flush() IOError: [Errno 9] Bad file descriptor
新人求助:wxpython在带有背景图的框架上显示静态文本
# ![图片说明](https://img-ask.csdn.net/upload/201904/20/1555748740_669215.png) 运行结果中的静态文本背景色我设为了蓝色,我希望不显示其背景色,希望有大神解答,非常感谢 class MyPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) try: image_file = 'background.jpg' to_bmp_image = wx.Image(image_file, wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.bitmap = wx.StaticBitmap(self, -1, to_bmp_image, (0, 0)) image_width = to_bmp_image.GetWidth() image_height = to_bmp_image.GetHeight() set_title = '%s %d x %d' % (image_file, to_bmp_image.GetWidth(), to_bmp_image.GetHeight()) parent.SetTitle(set_title) except IOError: print('Image file %s not found' % image_file) raise SystemExit self.button = wx.Button(self.bitmap, -1, label='Test', pos=(10,10)) st_tips = wx.StaticText(self ,0,u"sspu 停车管理系统",pos=(10,50)) st_tips.SetForegroundColour('white') st_tips.SetBackgroundColour('blue') if __name__ == '__main__': app = wx.PySimpleApp() frame = wx.Frame(None, -1, 'Image', size=(300,300)) my_panel = MyPanel(frame, -1) frame.Show() app.MainLoop() del app ``` ```
Py打包exe出现CA证书错误,怎么办?
单独在命令行里运行没错,打包成exe后运行出错。 错误: D:\1HelloWorld\PythonDeve\spider>D:\1HelloWorld\PythonDeve\spider\dist\baiduimg. exe Traceback (most recent call last): File "baiduimg.py", line 68, in <module> dataList = getManyPages('缇庡コ',2) File "baiduimg.py", line 46, in getManyPages urls.append(requests.get(url,params=i).json().get('data')) File "requests\api.pyc", line 72, in get File "requests\api.pyc", line 58, in request File "requests\sessions.pyc", line 508, in request File "requests\sessions.pyc", line 618, in send File "requests\adapters.pyc", line 407, in send File "requests\adapters.pyc", line 226, in cert_verify IOError: Could not find a suitable TLS CA certificate bundle, invalid path: D:\1 HelloWorld\PythonDeve\spider\dist\library.zip\certifi\cacert.pem ## **Python源码如下,求大佬回复** #coding=utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') import requests import os from time import ctime,sleep def getManyPages(keyword,pages): params=[] for i in range(30,30*pages+30,30): params.append({ 'tn': 'resultjson_com', 'ipn': 'rj', 'ct': 201326592, 'is': '', 'fp': 'result', 'queryWord': keyword, 'cl': 2, 'lm': -1, 'ie': 'utf-8', 'oe': 'utf-8', 'adpicid': '', 'st': -1, 'z': '', 'ic': 0, 'word': keyword, 's': '', 'se': '', 'tab': '', 'width': '', 'height': '', 'face': 0, 'istype': 2, 'qc': '', 'nc': 1, 'fr': '', 'pn': i, 'rn': 30, 'gsm': '1e', '1488942260214': '' }) url = 'https://image.baidu.com/search/acjson' urls = [] for i in params: urls.append(requests.get(url,params=i).json().get('data')) return urls def getImg(dataList, localPath): if not os.path.exists(localPath): # 新建文件夹 os.mkdir(localPath) x = 0 for list in dataList: for i in list: if i.get('thumbURL') != None: print('正在下载:%s' % i.get('thumbURL')) ir = requests.get(i.get('thumbURL')) open(localPath + '%d.jpg' % x, 'wb').write(ir.content) x += 1 else: print('图片链接不存在') if __name__ == '__main__': dataList = getManyPages('美女',2) # 参数1:关键字,参数2:要下载的页数 getImg(dataList,"D:\\Uarebeautiful\\") # 参数2:指定保存的路径
pyhon服务器如何用websocke实现服务器和html5的通信(代码已实现成功连接客户端服务端)?
服务端代码 #coding=gbk #coding=utf-8 #-*- coding: UTF-8 -* import struct import socket import re import time #ws握手响应头 import hashlib import base64 from multiprocessing import Process #HTML_ROOT_DIR = r"C:\Users\lenovo\Desktop\html" def write_msg(message): data=struct.pack('B',129)#写入第一个字节 msg_len=len(message)#写入包长度 if(msg_len<=125): data+=struct.pack('B',msg_len) elif(mas_len<=2**16-1): data+=struct.pack('!BH',126,msg_len) elif(mas_len<=2**64-1): data+=struct.pack('!BQ',127,msg_len) else: pass data+=bytes(message,encoding="utf-8") return data def handle_client(client_socket): """ 处理客户端请求 """ # 获取客户端请求数据 #获得key request_data = client_socket.recv(1024) print(request_data) webpage_regex=re.compile('''.*Sec-WebSocket-Key:(.*)''',re.IGNORECASE) key=webpage_regex.findall(request_data.decode("utf-8")) keyy='' try: print(key[0]) keyy=key[0] keyy=keyy.strip() print(keyy) except: pass # 打开文件,读取内容 try: file = open(r"C:\html\shouji\测试\客户端原生socket.html", "rb") except IOError: response_start_line = "HTTP/1.1 404 Not Found\r\n" response_headers = "Server: My server\r\n" response_body = "The file is not found!" response = response_start_line + response_headers + "\r\n" + response_body client_socket.send(bytes(response, "utf-8")) client_socket.close() else: file_data = file.read() file.close() if(keyy==''): response_start_line = "HTTP/1.1 200 OK\r\n" response_headers = "Server: My server\r\n" response_body = file_data.decode("utf-8") response = response_start_line + response_headers + "\r\n" + response_body client_socket.send(bytes(response, "utf-8")) client_socket.close() print('https响应已发送') else: magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' sha1 = hashlib.sha1() sha1.update((keyy+magic).encode("utf8")) keyy=base64.b64encode(sha1.digest()) print('dddddd',base64.b64encode(sha1.digest())) keyy=keyy.decode("utf8") print('***********************',keyy) response_start_line = "HTTP/1.1 101 Switching Protocols\r\n" response_headers = "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept:"+keyy+"\r\n" response_body = file_data.decode("utf-8") response = response_start_line + response_headers + "\r\n" #+ response_body client_socket.send(bytes(response, "utf-8")) print('ws响应已发送') while(1): time.sleep(5) client_socket.send(bytes('dddd', "utf-8")) #client_socket.send( write_msg('www.baidu.com')) print('发送了一次') # 关闭客户端连接 #client_socket.close() if __name__ == "__main__": server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(("0.0.0.0", 8000)) server_socket.listen(128) while True: client_socket, client_address = server_socket.accept() print("[%s, %s]用户连接上了" % client_address) handle_client_process = Process(target=handle_client, args=(client_socket,)) handle_client_process.start() #client_socket.close() 客户端代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h2 id="t">史p 芬</h2> <script type="text/javascript" charset="utf-8"> var ws = new WebSocket("ws://127.0.0.1:8000/"); //document.write(Date()); ws.onopen = function(e) { // Check the protocol chosen by the server //console.log(echoSocket.protocol); alert('连接上了') document.write(Date()); //ws.send('已经连接') } // 接受文本消息的事件处理实例: ws.onmessage = function(e) { alert('接受到消息') if(typeof e.data === "string"){ console.log("String message received", e, e.data); } else { console.log("Other message received", e, e.data); } }; ws.onclose = function(e) { alert('连接关闭') console.log("Connection closed", e); }; </script> </body> </html>
(可有偿求助)为什么Tensorflow生成TFRecord 代码失败?
``` import tensorflow as tf import os import random import math import sys from PIL import Image import numpy as np # In[2]: #验证集数量 _NUM_TEST = 500 #随机种子 _RANDOM_SEED = 0 #数据集路径 需要自己改动 DATASET_DIR = "D:/PycharmProjects/test/captcha/images" #tfrecord文件存放路径 需要自己改动 TFRECORD_DIR = "D:/PycharmProjects/test/captcha" #判断tfrecord文件是否存在 def _dataset_exists(dataset_dir): for split_name in ['train', 'test']: output_filename = os.path.join(dataset_dir,split_name + '.tfrecords') if not tf.gfile.Exists(output_filename): return False return True #获取所有验证码图片 def _get_filenames_and_classes(dataset_dir): photo_filenames = [] for filename in os.listdir(dataset_dir): #获取文件路径 path = os.path.join(dataset_dir, filename) photo_filenames.append(path) return photo_filenames def int64_feature(values): if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) def bytes_feature(values): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values])) def image_to_tfexample(image_data, label0, label1, label2, label3): #Abstract base class for protocol messages. return tf.train.Example(features=tf.train.Features(feature={ 'image': bytes_feature(image_data), 'label0': int64_feature(label0), 'label1': int64_feature(label1), 'label2': int64_feature(label2), 'label3': int64_feature(label3), })) #把数据转为TFRecord格式 def _convert_dataset(split_name, filenames, dataset_dir): assert split_name in ['train', 'test'] with tf.Session() as sess: #定义tfrecord文件的路径+名字 output_filename = os.path.join(TFRECORD_DIR,split_name + '.tfrecords') with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer: for i,filename in enumerate(filenames): try: sys.stdout.write('\r>> Converting image %d/%d' % (i+1, len(filenames))) sys.stdout.flush() #读取图片 image_data = Image.open(filename) #根据模型的结构resize 需要自己改 动 image_data = image_data.resize((224, 224)) #灰度化 image_data = np.array(image_data.convert('L')) #将图片转化为bytes image_data = image_data.tobytes() #获取label labels = filename.split('/')[-1][0:4] num_labels = [] for j in range(4): num_labels.append(int(labels[j])) #生成protocol数据类型 下面行 为了多任务学习拆成了4行 example = image_to_tfexample(image_data, num_labels[0], num_labels[1], num_labels[2], num_labels[3]) tfrecord_writer.write(example.SerializeToString()) except IOError as e: print('Could not read:',filename) print('Error:',e) print('Skip it\n') sys.stdout.write('\n') sys.stdout.flush() #判断tfrecord文件是否存在 if _dataset_exists(TFRECORD_DIR): print('tfcecord文件已存在') else: #获得所有图片 photo_filenames = _get_filenames_and_classes(DATASET_DIR) #把数据切分为训练集和测试集,并打乱 random.seed(_RANDOM_SEED) random.shuffle(photo_filenames) training_filenames = photo_filenames[_NUM_TEST:] testing_filenames = photo_filenames[:_NUM_TEST] #数据转换 _convert_dataset('train', training_filenames, DATASET_DIR) _convert_dataset('test', testing_filenames, DATASET_DIR) print('生成tfcecord文件') D:\Anaconda3\python.exe D:/PycharmProjects/test/10-2生成tfrecord文件.py >> Converting image 1/5811Traceback (most recent call last): File "D:/PycharmProjects/test/10-2生成tfrecord文件.py", line 118, in <module> _convert_dataset('train', training_filenames, DATASET_DIR) File "D:/PycharmProjects/test/10-2生成tfrecord文件.py", line 91, in _convert_dataset num_labels.append(int(labels[j])) ValueError: invalid literal for int() with base 10: 'i' ``` 我可以微信红包
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
字节跳动视频编解码面经
三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时想着能进去就不错了,管他哪个岗呢,就同意了面试...
开源一个功能完整的SpringBoot项目框架
福利来了,给大家带来一个福利。 最近想了解一下有关Spring Boot的开源项目,看了很多开源的框架,大多是一些demo或者是一个未成形的项目,基本功能都不完整,尤其是用户权限和菜单方面几乎没有完整的。 想到我之前做的框架,里面通用模块有:用户模块,权限模块,菜单模块,功能模块也齐全了,每一个功能都是完整的。 打算把这个框架分享出来,供大家使用和学习。 为什么用框架? 框架可以学习整体...
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
Spring Boot2 系列教程(十七)SpringBoot 整合 Swagger2
前后端分离后,维护接口文档基本上是必不可少的工作。 一个理想的状态是设计好后,接口文档发给前端和后端,大伙按照既定的规则各自开发,开发好了对接上了就可以上线了。当然这是一种非常理想的状态,实际开发中却很少遇到这样的情况,接口总是在不断的变化之中,有变化就要去维护,做过的小伙伴都知道这件事有多么头大!还好,有一些工具可以减轻我们的工作量,Swagger2 就是其中之一,至于其他类似功能但是却收费的软...
Python 基础(一):入门必备知识
目录1 标识符2 关键字3 引号4 编码5 输入输出6 缩进7 多行8 注释9 数据类型10 运算符10.1 常用运算符10.2 运算符优先级 1 标识符 标识符是编程时使用的名字,用于给变量、函数、语句块等命名,Python 中标识符由字母、数字、下划线组成,不能以数字开头,区分大小写。 以下划线开头的标识符有特殊含义,单下划线开头的标识符,如:_xxx ,表示不能直接访问的类属性,需通过类提供
天天学JAVA-JAVA基础(6)
如果觉得我写的还行,请关注我的博客并且点个赞哟。本文主要介绍JAVA 中最常使用字符串常量String相关知识。 1.String简介 2.创建字符串对象两种方式的区别 3.String常用的方法 4.String的不可变性 5.一道阿里面试题,你会做吗? 1.String简介 1.1String源码 首先看一段String源码,String主要实现了Serializable、Compar...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
2020 网络课 智慧树自动刷课代码,自动跳转,自动答题并关闭弹窗,自动1.5倍速静音
刷课一时爽,一直刷课一直爽! 终于让我找到了这个黑客代码了,教程开始: 只限谷歌浏览器和火狐浏览器使用,如果第一次失败,请重新试一下次 将下面代码复制后,进入浏览器按F12键,先点击console 然后Ctrl+v复制代码 最后按回车键即可 var ti = $("body"); var video = $(".catalogue_ul1 li[id*=video-]"); var i = 1;...
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
SQL-小白最佳入门sql查询一
一 说明 如果是初学者,建议去网上寻找安装Mysql的文章安装,以及使用navicat连接数据库,以后的示例基本是使用mysql数据库管理系统; 二 准备前提 需要建立一张学生表,列分别是id,名称,年龄,学生信息;本示例中文章篇幅原因SQL注释略; 建表语句: CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // dosho
致 Python 初学者
文章目录1. 前言2. 明确学习目标,不急于求成,不好高骛远3. 在开始学习 Python 之前,你需要做一些准备2.1 Python 的各种发行版2.2 安装 Python2.3 选择一款趁手的开发工具3. 习惯使用IDLE,这是学习python最好的方式4. 严格遵从编码规范5. 代码的运行、调试5. 模块管理5.1 同时安装了py2/py35.2 使用Anaconda,或者通过IDE来安装模
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
羞,Java 字符串拼接竟然有这么多姿势
二哥,我今年大二,看你分享的《阿里巴巴 Java 开发手册》上有一段内容说:“循环体内,拼接字符串最好使用 StringBuilder 的 append 方法,而不是 + 号操作符。”到底为什么啊,我平常一直就用的‘+’号操作符啊!二哥有空的时候能否写一篇文章分析一下呢? 就在昨天,一位叫小菜的读者微信我说了上面这段话。 我当时看到这条微信的第一感觉是:小菜你也太菜了吧,这都不知道为啥啊!我估...
写1行代码影响1000000000人,这是个什么项目?
不带钱不带卡,只带手机出门就能畅行无阻,这已是生活的常态。益普索发布的《2019第一季度第三方移动支付用户研究》报告显示,移动支付在手机网民中的渗透率高达95.1%,截至今年1月,支付宝全球用户数已经突破10亿。你或许每天都会打开支付宝,付款购物、领取权益、享受服务……但你或许不知道的是,在这个方便、快捷、智能化的APP背后,有一群年轻的技术人,用智慧和创新让它每天都变得更“聪明”一点。 ...
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
一点一滴记录 Java 8 stream 的使用
日常用到,一点一滴记录,不断丰富,知识积累,塑造自身价值。欢迎收藏 String 转 List String str = 1,2,3,4; List&lt;Long&gt; lists = Arrays.stream(str.split(",")).map(s -&gt; Long.parseLong(s.trim())).collect(Collectors.toList()); Lis...
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
相关热词 c# plc s1200 c#里氏转换原则 c# 主界面 c# do loop c#存为组套 模板 c# 停掉协程 c# rgb 读取图片 c# 图片颜色调整 最快 c#多张图片上传 c#密封类与密封方法
立即提问