def __init__(self, cell=None, width=None, height=None, directions=8, filename=None): if cell is None: cell = Cell self.Cell = cell self.display = makeDisplay(self) self.directions = directions if filename is not None: data = file(filename).readlines() if height is None: height = len(data) if width is None: width = max([len(x.rstrip()) for x in data]) if width is None: width = 20 if height is None: height = 20 self.width = width self.height = height self.image = None self.reset() if filename is not None: self.load(filename)
def stop(self): """ Stop the daemon """ # Get the pid from the pidfile try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = "pidfile %s does not exist. Daemon not running?\n" sys.stderr.write(message % self.pidfile) return # not an error in a restart # Try killing the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError as err: err = str(err) if err.find("No such process") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print(str(err)) sys.exit(1)
def load(self, f): if not hasattr(self.Cell, 'load'): return if isinstance(f, type('')): f = file(f) lines = f.readlines() lines = [x.rstrip() for x in lines] fh = len(lines) fw = max([len(x) for x in lines]) if fh > self.height: fh = self.height starty = 0 else: starty = (self.height - fh) / 2 if fw > self.width: fw = self.width startx = 0 else: startx = (self.width - fw) / 2 self.reset() for j in range(fh): line = lines[j] for i in range(min(fw, len(line))): self.grid[starty + j][startx + i].load(line[i])
def redraw(self): if not self.activated: return hexgrid = self.world.directions == 6 iw = self.world.width * self.size ih = self.world.height * self.size if hexgrid: iw += self.size / 2 f = file('temp.ppm', 'wb') f.write('P6\n%d %d\n255\n' % (iw, ih)) odd = False for row in self.world.grid: line = cStringIO.StringIO() if hexgrid and odd: line.write(self.getBackground() * (self.size / 2)) for cell in row: if len(cell.agents) > 0: c = self.getDataColour(cell.agents[-1]) else: c = self.getDataColour(cell) line.write(c * self.size) if hexgrid and not odd: line.write(self.getBackground() * (self.size / 2)) odd = not odd f.write(line.getvalue() * self.size) f.close() self.image = Tkinter.PhotoImage(file='temp.ppm') self.imageLabel.config(image=self.image)
def daemonize(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError as e: sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError as e: sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() si = file(self.stdin, 'r') so = file(self.stdout, 'a+') se = file(self.stderr, 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) if type(sys.stderr) is file: os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile, 'w+').write("%s\n" % pid)
def sendBankInfo(self): print('sendBankInfo') start = time.time() glob.stopFlag = 0 threads = list() f_file = file("./out.txt", "a+", encoding=glob.encode) picpath = self.picpathVar.get() if (glob.threadnum > 1): threadLock = threading.Lock() for i in range(glob.threadnum): print("i = "+ str(i)) startline = glob.get_value("thread_%d_linestart" % i) endline = glob.get_value("thread_%d_lineend" % i) print(startline, endline) data = self.datalines print(data) data = data[int(startline):int(endline + 1)] #print(data) if startline == 0: self.returns.delete('1.0', 'end') threadName = ("thread_%d" % i) thread = mythread(threadName, threadLock, startline, bankinfo, self.returns, picpath, self.pictypevaluebak, self.URL, f_file, data) thread.start() time.sleep(0.01) #threads.append(thread) ''' for thread in threads: thread.join() ''' else: datalines = func.getBankInfo(self.dataPathVar) print(datalines) print('linenum = %s' % (glob.linenum)) datalines = datalines[glob.linenum:] if glob.linenum == 0: self.returns.delete('1.0', 'end') func.sendInfo(bankinfo, self.returns, picpath, self.pictypevaluebak, self.URL, f_file, datalines) del(f_file) end = time.time() print('耗时:%s' % (end - start))
def removeColCSV(csvfile) : if csvfile.find('_all') != -1 : print(csvfile) newCSVName = csvfile.split('_')[2] c = file(newCSVName,'wb') cToRead = file(csvfile,'rb') reader = csv.reader(cToRead) writer = csv.writer(c) writer.writerow('date','hour','type','dongsi') counter = 0 writeData = [] for line in reader : print(line) counter = counter + 1 if counter % 5 == 0 or counter%5 == 4 : writeData.append((line[0],line[1],line[2],line[3])) cToRead.close() writer.writerows(writeData) c.close()
def save(self, f=None): if not hasattr(self.Cell, 'save'): return if isinstance(f, type('')): f = file(f, 'w') total = '' for j in range(self.height): line = '' for i in range(self.width): line += self.grid[j][i].save() total += '%s\n' % line if f is not None: f.write(total) f.close() else: return total
def start(self): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if pid: message = "pidfile %s already exist. Daemon already running?\n" sys.stderr.write(message % self.pidfile) sys.exit(1) # Start the daemon self.daemonize() self.run()
# -*- coding: utf-8 -*- from PyPDF2 import PdfFileWriter, PdfFileReader import file output = PdfFileWriter() input1 = PdfFileReader(file("document1.pdf", "rb")) watermark = PdfFileReader(file("watermark.pdf", "rb")) page4.mergePage(watermark.getPage(0)) # finally, write "output" to document-output.pdf outputStream = file("document-output.pdf", "wb") output.write(outputStream) outputStream.close()
#!env python import random import string import file secret = ''.join([random.SystemRandom().choice("{}{}{}".format( string.ascii_letters, string.digits, string.punctuation)) for i in range(50)]) f = file('/run/app/django_secret', 'w') f.write(secret) f.close()
#!env python import random import string import file secret = ''.join([ random.SystemRandom().choice("{}{}{}".format(string.ascii_letters, string.digits, string.punctuation)) for i in range(50) ]) f = file('/run/app/django_secret', 'w') f.write(secret) f.close()
# -*- coding: utf-8 -*- ''' Created on 2017��1��3�� @author: Tan Zhuqing ''' import csv, file reader = csv.reader(file('filter_user.csv', 'rb')) csvfile = file('9_1_data.csv', 'wb') wrtiter1 = csv.writer(csvfile) csvfile = file('9_3_data.csv', 'wb') wrtiter2 = csv.writer(csvfile) csvfile = file('9_7_data.csv', 'wb') wrtiter3 = csv.writer(csvfile) csvfile = file('9_all_data.csv', 'wb') wrtiter4 = csv.writer(csvfile) positive_user_item = set() num = 0 for line in reader: if num == 0: num = num + 1 continue time_s = line[5].split(' ') time_slot = time_s[0].split('-') month = int(time_slot[1])
def load(fileName): """Return a thing loaded from a file.""" f = file(fileName, "r") obj = pickle.load(f) f.close() return obj
def save(self, fileName): """Save thing to a file.""" f = file(fileName, "w") pickle.dump(self, f) f.close()