Search Results

Search found 13693 results on 548 pages for 'python metaprogramming'.

Page 125/548 | < Previous Page | 121 122 123 124 125 126 127 128 129 130 131 132  | Next Page >

  • importing symbols from python package into caller's namespace

    - by Paul C
    I have a little internal DSL written in a single Python file that has grown to a point where I would like to split the contents across a number of different directories + files. The new directory structure currently looks like this: dsl/ __init__.py types/ __init__.py type1.py type2.py and each type file contains a class (e.g. Type1). My problem is that I would like to keep the implementation of code that uses this DSL as simple as possible, something like: import dsl x = Type1() ... This means that all of the important symbols should be available directly in the user's namespace. I have tried updating the top-level __init__.py file to import the relevant symbols: from types.type1 import Type1 from types.type2 import Type2 ... print globals() the output shows that the symbols are imported correctly, but they still aren't present in the caller's code (the code that's doing the import dsl). I think that the problem is that the symbols are actually being imported to the 'dsl' namespace. How can I change this so that the classes are also directly available in the caller's namespace?

    Read the article

  • python list Index out of range error

    - by dman762000
    I am working on a python tetris game that my proffessor assigned for the final project of a concepts of programming class. I have got just about everything he wanted to work on it at this point but I am having a slight problem with one part of it. Whenever I start moving pieces left and right I keep getting "index out of range error". This only happens when it is up against a piece. Here are the culprits that are giving me grief. def clearRight(block=None): global board, activeBlock, stackedBlocks isClear = True if(block == None): block = activeBlock if(block != None): for square in block['squares']: row = square[1] col = square[0]+1 if(col >= 0 and stackedBlocks[row][col] !=None): isClear=False return isClear def clearLeft(block=None): global board, activeBlock, stackedBlocks isClear = True if(block == None): block = activeBlock if(block != None): for square in block['squares']: row = square[1] col = square[0]-1 if(col >= 0 and stackedBlocks[row][col] !=None): isClear=False return isClear I am not looking to get anyone to fix it for me, I'm only looking for tips on how to fix it myself. Thanks in advance for any help that is given.

    Read the article

  • parse a special xml in python

    - by zhaojing
    I have s special xml file like below: <alarm-dictionary source="DDD" type="ProxyComponent"> <alarm code="402" severity="Alarm" name="DDM_Alarm_402"> <message>Database memory usage low threshold crossed</message> <description>dnKinds = database type = quality_of_service perceived_severity = minor probable_cause = thresholdCrossed additional_text = Database memory usage low threshold crossed </description> </alarm> ... </alarm-dictionary> I know in python, I can get the "alarm code", "severity" in tag alarm by: for alarm_tag in dom.getElementsByTagName('alarm'): if alarm_tag.hasAttribute('code'): alarmcode = str(alarm_tag.getAttribute('code')) And I can get the text in tag message like below: for messages_tag in dom.getElementsByTagName('message'): messages = "" for message_tag in messages_tag.childNodes: if message_tag.nodeType in (message_tag.TEXT_NODE, message_tag.CDATA_SECTION_NODE): messages += message_tag.data But I also want to get the value like dnkind(database), type(quality_of_service), perceived_severity(thresholdCrossed) and probable_cause(Database memory usage low threshold crossed ) in tag description. That is, I also want to parse the content in the tag in xml. Could anyone help me with this? Thanks a lot!

    Read the article

  • List modification in Python

    - by user2945143
    We are given an algorithm to modify a list of numbers from 1 to 28. There are 5 steps in the algorithm. We have written functions for each step (all correct). We need to write a function that combines all 5 steps. The algorithm modifies the list to get a value. Each time you get a new value, you use the list created by the algorithm from the previous step. This is what we have gotten so far for the code: get_card_at_top_index(insert_top_to_bottom(triple_cut((move_joker_2( move_joker_1(deck)))))) When we run the code to generate the get_card_at_top_index, the first answer is correct. However, the rest are not. Instead of using from the new list, python uses the value that it generated from the last step. What did we do wrong? UPDATE: The other 5 codes passed the tests, they are correct. Code 1 (List) = list1 Code 2 (list1) = list2 Code 3 (list2) = list3 Code 4 (list3) = list4 Code 5 (list4) = list5 we generate a number from 5. We need to run the algorithm again to generate 25 more numbers. We will use list 5 start from step 1

    Read the article

  • Python-based password tracker (or dictionary)

    - by Arrieta
    Hello: Where we work we need to remember about 10 long passwords which need to change every so often. I would like to create a utility which can potentially save these passwords in an encrypted file so that we can keep track of them. I can think of some sort of dictionary passwd = {'host1':'pass1', 'host2':'pass2'}, etc, but I don't know what to do about encryption (absolutely zero experience in the topic). So, my question is really two questions: Is there a Linux-based utility which lets you do that? If you were to program it in Python, how would you go about it? A perk of approach two, would be for the software to update the ssh public keys after the password has been changed (you know the pain of updating ~15 tokens once you change your password). As it can be expected, I have zero control over the actual network configuration and the management of scp keys. I can only hope to provide a simple utility to me an my very few coworkers so that, if we need to, we can retrieve a password on demand. Cheers.

    Read the article

  • html in do_GET() method of a simple Python webserver

    - by Meeri_Peeri
    I am relatively new to Python but have been doing a lot of different things with it recently and I am liking it a lot. However, I ran into trouble/block with the following code. import http.server import socketserver import glob import random class Server(http.server.SimpleHTTPRequestHandler): def do_GET(self): self.send_response(200, 'OK') self.send_header('Content-type', 'html') self.end_headers() self.wfile.write(bytes("<html> <head><title> Hello World </title> </head> <body>", 'UTF-8')) images = glob.glob('*.jpg') rand = random.randint(0,len(images)-1) imagestring = "<img src = \"" + images[rand] + "\" height = 1028 width = 786 align = \"right\"/> </body> </html>" self.wfile.write(bytes(imagestring, 'UTF-8')) def serve_forever(port): socketserver.TCPServer(('', port), Server).serve_forever() if __name__ == "__main__": Server.serve_forever(8000) What I am trying to do here is grab a random image from multiple images in the directory and add it into the response to a web request. The code works fine but when I access the server via browser, the image is not displayed. The html of the page is as intended though. The permissions on the files are 755. Also I tried to create an index.html file in the do_GET method. That didn't work either. I mean the index.html was generated fine, but the response in the browser this time did not show anything (not even the hello world in the title). Am I missing anything very simple here? I was thinking should I overload the handle_request of the underlying SocketServer.BaseServer as the documentation says you should never override BaseHTTPServer's handle() method and should rather override the corresponding do_* method?

    Read the article

  • Filtering string in Python

    - by Ecce_Homo
    I am making algorithm for checking the string (e-mail) - like "E-mail addres is valid" but their are rules. First part of e-mail has to be string that has 1-8 characters (can contain alphabet, numbers, underscore [ _ ]...all the parts that e-mail contains) and after @ the second part of e-mail has to have string that has 1-12 characters (also containing all legal expressions) and it has to end with top level domain .com EDIT email = raw_input ("Enter the e-mail address:") length = len (email) if length > 20 print "Address is too long" elif lenght < 5: print "Address is too short" if not email.endswith (".com"): print "Address doesn't contain correct domain ending" first_part = len (splitting[0]) second_part = len(splitting[1]) account = splitting[0] domain = splitting[1] for c in account: if c not in "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.": print "Invalid char", "->", c,"<-", "in account name of e-mail" for c in domain: if c not in "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.": print "Invalid char", "->", c,"<-", "in domain of e-mail" if first_part == 0: print "You need at least 1 character before the @" elif first_part> 8: print "The first part is too long" if second_part == 4: print "You need at least 1 character after the @" elif second_part> 16: print "The second part is too long" else: # if everything is fine return this print "E-mail addres is valid" EDIT: After reproting what is wrong with our input, now I need to make Python recognize valid address and return ("E-mail adress is valid") This is the best i can do with my knowledge....and we cant use regular expressions, teacher said we are going to learn them later.

    Read the article

  • Returning JSON from JavaScript to Python

    - by Chris Lacy
    I'm writing a simple App Engine app. I have a simple page that allows a user to move a marker on a Google map instance. Each time the user drops the marker, I want to return the long/lat to my Python app. function initialize() { ... // Init map var marker = new GMarker(center, {draggable: true}); GEvent.addListener(marker, "dragend", function() { // I want to return the marker.x/y to my app when this function is called .. }); } To my (admittedly limited) knowledge, I should be: 1). Returning a JSON structure with my required data in the listener callback above 2). In my webapp.RequestHandler Handler class, trying to retrieve the JSON structure during the post method. I would very much like to pass this JSOn data back to the app without causing a page reload (which is what has happened when I've used various post/form.submit methods so far). Can anyone provide me with some psuedo code or an example on how I might achieve what I'm after? Thanks.

    Read the article

  • python recursive iteration exceeding limit for tree implementation

    - by user3698027
    I'm implementing a tree dynamically in python. I have defined a class like this... class nodeobject(): def __init__(self,presentnode=None,parent=None): self.currentNode = presentnode self.parentNode = parent self.childs = [] I have a function which gets possible childs for every node from a pool def findchildren(node, childs): # No need to write the whole function on how it gets childs Now I have a recursive function that starts with the head node (no parent) and moves down the chain recursively for every node (base case being the last node having no children) def tree(dad,children): for child in children: childobject = nodeobject(child,dad) dad.childs.append(childobject) newchilds = findchildren(child, children) if len(newchilds) == 0: lastchild = nodeobject(newchilds,childobject) childobject.childs.append(lastchild) loopchild = copy.deepcopy(lastchild) while loopchild.parentNode != None: print "last child" else: tree(childobject,newchilds) The tree formation works for certain number of inputs only. Once the pool gets bigger, it results into "MAXIMUM RECURSION DEPTH EXCEEDED" I have tried setting the recursion limit with set.recursionlimit() and it doesn't work. THe program crashes. I want to implement a stack for recursion, can someone please help, I have gone no where even after trying for a long time ?? Also, is there any other way to fix this other than stack ?

    Read the article

  • Unit Testing Interfaces in Python

    - by Nicholas Mancuso
    I am currently learning python in preperation for a class over the summer and have gotten started by implementing different types of heaps and priority based data structures. I began to write a unit test suite for the project but ran into difficulties into creating a generic unit test that only tests the interface and is oblivious of the actual implementation. I am wondering if it is possible to do something like this.. suite = HeapTestSuite(BinaryHeap()) suite.run() suite = HeapTestSuite(BinomialHeap()) suite.run() What I am currently doing just feels... wrong (multiple inheritance? ACK!).. class TestHeap: def reset_heap(self): self.heap = None def test_insert(self): self.reset_heap() #test that insert doesnt throw an exception... for x in self.inseq: self.heap.insert(x) def test_delete(self): #assert we get the first value we put in self.reset_heap() self.heap.insert(5) self.assertEquals(5, self.heap.delete_min()) #harder test. put in sequence in and check that it comes out right self.reset_heap() for x in self.inseq: self.heap.insert(x) for x in xrange(len(self.inseq)): val = self.heap.delete_min() self.assertEquals(val, x) class BinaryHeapTest(TestHeap, unittest.TestCase): def setUp(self): self.inseq = range(99, -1, -1) self.heap = BinaryHeap() def reset_heap(self): self.heap = BinaryHeap() class BinomialHeapTest(TestHeap, unittest.TestCase): def setUp(self): self.inseq = range(99, -1, -1) self.heap = BinomialHeap() def reset_heap(self): self.heap = BinomialHeap() if __name__ == '__main__': unittest.main()

    Read the article

  • Python lists/arrays: disable negative indexing wrap-around

    - by wim
    While I find the negative number wraparound (i.e. A[-2] indexing the second-to-last element) extremely useful in many cases, there are often use cases I come across where it is more of an annoyance than helpful, and I find myself wishing for an alternate syntax to use when I would rather disable that particular behaviour. Here is a canned 2D example below, but I have had the same peeve a few times with other data structures and in other numbers of dimensions. import numpy as np A = np.random.randint(0, 2, (5, 10)) def foo(i, j, r=2): '''sum of neighbours within r steps of A[i,j]''' return A[i-r:i+r+1, j-r:j+r+1].sum() In the slice above I would rather that any negative number to the slice would be treated the same as None is, rather than wrapping to the other end of the array. Because of the wrapping, the otherwise nice implementation above gives incorrect results at boundary conditions and requires some sort of patch like: def ugly_foo(i, j, r=2): def thing(n): return None if n < 0 else n return A[thing(i-r):i+r+1, thing(j-r):j+r+1].sum() I have also tried zero-padding the array or list, but it is still inelegant (requires adjusting the lookup locations indices accordingly) and inefficient (requires copying the array). Am I missing some standard trick or elegant solution for slicing like this? I noticed that python and numpy already handle the case where you specify too large a number nicely - that is, if the index is greater than the shape of the array it behaves the same as if it were None.

    Read the article

  • Python/Sqlite app for web or desktop?

    - by ChrisC
    I am in the planning stages of rewriting an Access db I wrote several years ago in a full fledged program. I have very slight experience coding, but not enough to call myself a programmer by far. I'll definitely be learning as I go, so I'd like to keep everything as simple as possible. I've decided on Python and SQLite for my program, but I need help on my next decision. Here is my situation 1) It'll be a desktop program, run locally on each machine, all Windows 2) I want a nice looking GUI with colors, different shaped buttons, nice menus, lists, etc, etc 3) I'm thinking about using a browser interface because (a) from what I've read, browser apps can look really great, and (b) I understand there are lots of free tools to assist in setting up the GUI/GUI code with drag and drop tools, so that helps my "keep it simple" goal. 4) I want the program to be totally portable so it runs completely from one single folder on a user's PC. If I do go the browser app router, a major concern I have is the possibility that a user's browser settings could affect or break the app. How likely is this? What other pros and cons are there for my situation?

    Read the article

  • Please help me optimize my Python code

    - by Haidon
    Beginner here! Forgive me in advance for raising what is probably an incredibly simple problem. I've been trying to put together a Python script that runs multiple find-and-replace actions and a few similar things on a specified plain-text file. It works, but from a programming perspective I doubt it works well. How would I best go about optimizing the actions made upon the 'outtext' variable? At the moment it's basically doing a very similar thing four times over... import binascii import re import struct import sys infile = sys.argv[1] charenc = sys.argv[2] outFile=infile+'.tex' findreplace = [ ('TERM1', 'TERM2'), ('TERM3', 'TERM4'), ('TERM5', 'TERM6'), ] inF = open(infile,'rb') s=unicode(inF.read(),charenc) inF.close() # THIS IS VERY MESSY. for couple in findreplace: outtext=s.replace(couple[0],couple[1]) s=outtext for couple in findreplace: outtext=re.compile('Title: (.*)', re.I).sub(r'\\title'+ r'{\1}', s) s=outtext for couple in findreplace: outtext=re.compile('Author: (.*)', re.I).sub(r'\\author'+ r'{\1}', s) s=outtext for couple in findreplace: outtext=re.compile('Date: (.*)', re.I).sub(r'\\date'+ r'{\1}', s) s=outtext # END MESSY SECTION. outF = open(outFile,'wb') outF.write(outtext.encode('utf-8')) outF.close()

    Read the article

  • How to parse multiple dates from a block of text in Python (or another language)

    - by mlissner
    I have a string that has several date values in it, and I want to parse them all out. The string is natural language, so the best thing I've found so far is dateutil. Unfortunately, if a string has multiple date values in it, dateutil throws an error: >>> s = "I like peas on 2011-04-23, and I also like them on easter and my birthday, the 29th of July, 1928" >>> parse(s, fuzzy=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/pymodules/python2.7/dateutil/parser.py", line 697, in parse return DEFAULTPARSER.parse(timestr, **kwargs) File "/usr/lib/pymodules/python2.7/dateutil/parser.py", line 303, in parse raise ValueError, "unknown string format" ValueError: unknown string format Any thoughts on how to parse all dates from a long string? Ideally, a list would be created, but I can handle that myself if I need to. I'm using Python, but at this point, other languages are probably OK, if they get the job done. PS - I guess I could recursively split the input file in the middle and try, try again until it works, but it's a hell of a hack.

    Read the article

  • python script problem once build and package it

    - by Apache
    hi expert, I've written python script to scan wifi and send data to the server, I set interval value, so it keep on scanning and send the data, it read from config.txt file where i set the interval value to scan, I also add yes/no in my config file, so is 'no' it will scan only once and if 'yes' it will scan according to the interval level, my code as below import time,..... from threading import Event, Thread class RepeatTimer(Thread): def __init__(self, interval, function, iterations=0, args=[], kwargs={}): Thread.__init__(self) self.interval = interval self.function = function self.iterations = iterations self.args = args self.kwargs = kwargs self.finished = Event() def run(self): count = 0 while not self.finished.is_set() and (self.iterations <= 0 or count < self.iterations): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) count += 1 def cancel(self): self.finished.set() def scanWifi(self): #scanning process and sending data done here obj = JW() if status == "yes": t = RepeatTimer(int(intervalTime),obj.scanWifi) t.start() else: obj.scanWifi() once I package my code, its only run when I set my config file set to 'no' where it scan only once, but when I set my config file to 'yes', there is no progress at all, so I found that there is problem with my class RepeatTimer(Timer) once build, but don't know how to solve can anyone help me thanks

    Read the article

  • SFTP in Python? (platform independent)

    - by Mark Wilbur
    I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy: import ftplib info= ('someuser', 'password') #hard-coded def putfile(file, site, dir, user=(), verbose=True): """ upload a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax. import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' Thanks again!

    Read the article

  • Unknown reason for code executing the way it does in python

    - by Jasper
    Hi I am a beginner programmer, using python on Mac. I created a function as a part of a game which receives the player's input for the main character's name. The code is: import time def newGameStep2(): print ' ****************************************** ' print '\nStep2\t\t\t\tCharacter Name' print '\nChoose a name for your character. This cannot\n be changed during the game. Note that there\n are limitations upon the name.' print '\nLimitations:\n\tYou cannot use:\n\tCommander\n\tLieutenant\n\tMajor\n\t\tas these are reserved.\n All unusual capitalisations will be removed.\n There is a two-word-limit on names.' newStep2Choice = raw_input('>>>') newStep2Choice = newStep2Choice.lower() if 'commander' in newStep2Choice or 'lieutenant' in newStep2Choice or 'major' in newStep2Choice: print 'You cannot use the terms \'commander\', \'lieutenant\' or \'major\' in the name. They are reserved.\n' print time.sleep(2) newGameStep2() else: newStep2Choice = newStep2Choice.split(' ') newStep2Choice = [newStep2Choice[0].capitalize(), newStep2Choice[1].capitalize()] newStep2Choice = ' ' .join(newStep2Choice) return newStep2Choice myVar = newGameStep2() print myVar When I was testing, I inputted 'major a', and when it asked me to input another name, i inputted 'a b'. However, when it returned the output of the function, it returns 'major a'. I went through this with a debugger, yet I still can't seem to find where the problem occurred. Thanks for any help, Jasper

    Read the article

  • How to check volume is mounted or not using python with a dynamic volume name

    - by SR query
    import subprocess def volumeCheck(volume_name): """This function will check volume name is mounted or not. """ volume_name = raw_input('Enter volume name:') volumeCheck(volume_name) print 'volume_name=',volume_name p = subprocess.Popen(['df', '-h'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p1, err = p.communicate() pattern = p1 if pattern.find(volume_name): print 'volume found' else: print 'volume not found' While running i always got wrong result "volume found". root@sr-query:/# df -h Filesystem Size Used Avail Use% Mounted on rootfs 938M 473M 418M 54% / /dev/md0 938M 473M 418M 54% / none 250M 4.9M 245M 2% /dev /dev/md2 9.7M 1.2M 8.0M 13% /usr/config /dev/md7 961M 18M 895M 2% /downloads tmpfs 250M 7.9M 242M 4% /var/volatile tmpfs 250M 0 250M 0% /dev/shm tmpfs 250M 0 250M 0% /media/ram **/dev/mapper/vg9-lv9 1016M 65M 901M 7% /VolumeData/sp /dev/mapper/vg10-lv10 1016M 65M 901M 7% /VolumeData/cp** root@sr-query:/# root@sr-query:/# root@sr-query:/# python volume_check.py Enter volume name:raid_10volume volume_name= raid_10volume **volume found** root@sr-query:/# I enterd raid_10volume its not listed here please check the df -h command out put(only 2 volume there sp and cp) , then how it reached else part. what is wrong in my code? Thanks in advance. is there any other way to do this work ! ?

    Read the article

  • how do I remove rows/columns from this matrix using python

    - by banditKing
    My matrix looks like this. ['Hotel', ' "excellent"', ' "very good"', ' "average"', ' "poor"', ' "terrible"', ' "cheapest"', ' "rank"', ' "total reviews"'] ['westin', ' 390', ' 291', ' 70', ' 43', ' 19', ' 215', ' 27', ' 813'] ['ramada', ' 136', ' 67', ' 53', ' 30', ' 24', ' 149', ' 49', ' 310 '] ['sutton place', '489', ' 293', ' 106', ' 39', ' 20', ' 299', ' 24', ' 947'] ['loden', ' 681', ' 134', ' 17', ' 5', ' 0', ' 199', ' 4', ' 837'] ['hampton inn downtown', ' 241', ' 166', ' 26', ' 5', ' 1', ' 159', ' 21', ' 439'] ['shangri la', ' 332', ' 45', ' 20', ' 8', ' 2', ' 325', ' 8', ' 407'] ['residence inn marriott', ' 22', ' 15', ' 5', ' 0', ' 0', ' 179', ' 35', ' 42'] ['pan pacific', ' 475', ' 262', ' 86', ' 29', ' 16', ' 249', ' 15', ' 868'] ['sheraton wall center', ' 277', ' 346', ' 150', ' 80', ' 26', ' 249', ' 45', ' 879'] ['westin bayshore', ' 390', ' 291', ' 70', ' 43', ' 19', ' 199', ' 813'] I want to remove the top row and the 0th column from this and create a new matrix. How do I do this? Normally in java or so Id use the following code: for (int y; y< matrix[x].length; y++) for(int x; x < matrix[Y].length; x++) { if(x == 0 || y == 0) { continue } else { new_matrix[x][y] = matrix[x][y]; } } Is there a way such as this in python to iterate and selectively copy elements? Thanks EDIT Im also trying to convert each matrix element from a string to a float as I iterate over the matrix. This my updated modified code based on the answer below. A = [] f = open("csv_test.csv",'rt') try: reader = csv.reader(f) for row in reader: A.append(row) finally: f.close() new_list = [row[1:] for row in A[1:]] l = np.array(new_list) l.astype(np.float32) print l However Im getting an error --> l.astype(np.float32) print l ValueError: setting an array element with a sequence.

    Read the article

  • SCons and dependencies for python function generating source

    - by elmo
    I have an input file data, a python function parse and a template. What I am trying to do is use parse function to get dictionary out of data and use that to replace fields in template. Now to make this a bit more generic (I perform the same action in few places) I have defined a custom function to do so. Below is definition of custom builder and values is a dictionary with { 'name': (data_file, parse_function) } (you don't really need to read through this, I simply put it here for completeness). def TOOL_ADD_FILL_TEMPLATE(env): def FillTemplate(env, output, template, values): out = output[0] subs = {} for name, (node, process) in values.iteritems(): def Process(env, target, source): with open( env.GetBuildPath(target[0]), 'w') as out: out.write( process( source[0] ) ) builder = env.Builder( action = Process ) subs[name] = builder( env, env.GetBuildPath(output[0])+'_'+name+'_processed.cpp', node )[0] def Fill(env, target, source): values = dict( (name, n.get_contents()) for name, n in subs.iteritems() ) contents = template[0].get_contents().format( **values ) open( env.GetBuildPath(target[0]), 'w').write( contents ) builder = env.Builder( action = Fill ) builder( env, output[0], template + subs.values() ) return output env.Append(BUILDERS = {'FillTemplate': FillTemplate}) It works fine when it comes to checking if data or template changed. If it did it rebuilds the output. It even works if I edit process function directly. However if my process function looks like this: def process( node ): return subprocess(node) and I edit subprocess the change goes unnoticed. Is there any way to get correct builds without making process functions being always invoked?

    Read the article

  • OS-independent Inter-program communication between Python and C

    - by Gyppo
    I have very little idea what I'm doing here, I've never done anything like this before, but a friend and I are writing competing chess programs and they need to be able to communicate to each other. He'll be writing mainly in C, the bulk of mine will be in Python, and I can see a few options: Alternately write to a temp file, or successive temp files. As the communication won't be in any way bulky this could work, but seems like an ugly work-around to me, the programs will have to keep checking for change/new files, it just seems ugly. Find some way of manipulating pipes i.e. mine.py| ./his . This seems like a bit of a dead end. Use sockets. But I don't know what I'd be doing, so could someone give me a pointer to some reading material? I'm not sure if there are OS-independent, language independent methods. Would there have to be some kind of supervisor server program to administrate? Use some kind of HTML protocol, which seems like overkill. I don't mind the programs having to run on the same machine. What do people recommend, and where can I start reading?

    Read the article

  • Random Loss of precision in Python ReadLine()

    - by jackyouldon
    Hi all, We have a process which takes a very large csv (1.6GB) and breaks it down into pieces (in this case 3). This runs nightly and normally doesn't give us any problems. When it ran last night, however, the first of the output files had lost precision on the numeric fields in the data. The active ingredient in the script are the lines: while lineCounter <= chunk: oOutFile.write(oInFile.readline()) lineCounter = lineCounter + 1 and the normal output might be something like StringField1; StringField2; StringField3; StringField4; 1000000; StringField5; 0.000054454 etc. On this one occasion and in this one output file the numeric fields were all output with 6 zeros at the end i.e. StringField1; StringField2; StringField3; StringField4; 1000000.000000; StringField5; 0.000000 We are using Python v2.6 (and don't want to upgrade unless we really have to) but we can't afford to lose this data. Does anyone have any idea why this might have happened? If the readline is doing some kind of implicit conversion is there a way to do a binary read, because we really just want this data to pass through untouched? It is very wierd to us that this only affected one of the output files generated by the same script, and when it was rerun the output was as expected. thanks Jack

    Read the article

  • Python client / server question

    - by AustinM
    I'm working on a bit of a project in python. I have a client and a server. The server listens for connections and once a connection is received it waits for input from the client. The idea is that the client can connect to the server and execute system commands such as ls and cat. This is my server code: import sys, os, socket host = '' port = 50105 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) print("Server started on port: ", port) s.listen(5) print("Server listening\n") conn, addr = s.accept() print 'New connection from ', addr while (1): rc = conn.recv(5) pipe = os.popen(rc) rl = pipe.readlines() file = conn.makefile('w', 0) file.writelines(rl[:-1]) file.close() conn.close() And this is my client code: import sys, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = 'localhost' port = input('Port: ') s.connect((host, port)) cmd = raw_input('$ ') s.send(cmd) file = s.makefile('r', 0) sys.stdout.writelines(file.readlines()) When I start the server I get the right output, saying the server is listening. But when I connect with my client and type a command the server exits with this error: Traceback (most recent call last): File "server.py", line 21, in <module> rc = conn.recv(2) File "/usr/lib/python2.6/socket.py", line 165, in _dummy raise error(EBADF, 'Bad file descriptor') socket.error: [Errno 9] Bad file descriptor On the client side, I get the output of ls but the server gets screwed up.

    Read the article

  • Python threading question (Working with a method that blocks forever)

    - by Nix
    I am trying to wrap a thread around some receiving logic in python. Basically we have an app, that will have a thread in the background polling for messages, the problem I ran into is that piece that actually pulls the messages waits forever for a message. Making it impossible to terminate... I ended up wrapping the pull in another thread, but I wanted to make sure there wasn't a better way to do it. Original code: class Manager: def __init__(self): receiver = MessageReceiver() receiver.start() #do other stuff... class MessageReceiver(Thread): receiver = Receiver() def __init__(self): Thread.__init__(self) def run(self): #stop is a flag that i use to stop the thread... while(not stopped ): #can never stop because pull below blocks message = receiver.pull() print "Message" + message What I refectored to: class Manager: def __init__(self): receiver = MessageReceiver() receiver.start() class MessageReceiver(Thread): receiver = Receiver() def __init__(self): Thread.__init__(self) def run(self): pullThread = PullThread(self.receiver) pullThread.start() #stop is a flag that i use to stop the thread... while(not stopped and pullThread.last_message ==None): pass message = pullThread.last_message print "Message" + message class PullThread(Thread): last_message = None def __init__(self, receiver): Thread.__init(self, target=get_message, args=(receiver)) def get_message(self, receiver): self.last_message = None self.last_message = receiver.pull() return self.last_message I know the obvious locking issues exist, but is this the appropriate way to control a receive thread that waits forever for a message? One thing I did notice was this thing eats 100% cpu while waiting for a message... **If you need to see the stopping logic please let me know and I will post.

    Read the article

  • Python, web log data mining for frequent patterns

    - by descent
    Hello! I need to develop a tool for web log data mining. Having many sequences of urls, requested in a particular user session (retrieved from web-application logs), I need to figure out the patterns of usage and groups (clusters) of users of the website. I am new to Data Mining, and now examining Google a lot. Found some useful info, i.e. querying Frequent Pattern Mining in Web Log Data seems to point to almost exactly similar studies. So my questions are: Are there any python-based tools that do what I need or at least smth similar? Can Orange toolkit be of any help? Can reading the book Programming Collective Intelligence be of any help? What to Google for, what to read, which relatively simple algorithms to use best? I am very limited in time (to around a week), so any help would be extremely precious. What I need is to point me into the right direction and the advice of how to accomplish the task in the shortest time. Thanks in advance!

    Read the article

< Previous Page | 121 122 123 124 125 126 127 128 129 130 131 132  | Next Page >