2,646 Posted Topics
Re: There is no reason to avoid it, it's a standard construct in python which means 'repeat indefinitely'. You can use [icode]while True:[/icode] which is semantically better, but it doesn't change much. | |
Re: re.search returns a 'match object' or None. Follow this example [code=python] >>> mo = re.search(r"b\w+", "'Give me bacon and eggs,' said the other man.") >>> mo <_sre.SRE_Match object at 0x7f90947e2e68> >>> mo.group(0) 'bacon' [/code] | |
Re: I have a good link about unicode [url]http://farmdev.com/talks/unicode/[/url] | |
Re: If f is a fraction, you can use f.denominator and f.numerator. See also this snippet [url]http://www.daniweb.com/code/snippet223956.html[/url]. | |
Re: If you only have the .pyc files (and not the .py files), the best solution is to install a version of python 2.5 on your system and run the installer with this version of python. You can have several versions of python on the same system (I currently use 2.5, … | |
Re: The problem is that you convert [b]twice[/b] the angles to degrees. For example the part [icode]if type == "SSS"[/icode] should look like [code=python] if type=="SSS": print("\nYou picked SSS. Type in each number, seperated by a space\n") nums=input("Numbers:\t").split() nums=[float(eval(i)) for i in nums] resultdict=SSS(nums[0],nums[1],nums[2]) # LINE SUPPRESSED print("\nsides:\t ", resultdict["sides"], " … | |
Re: You should probably write [code=python] print usps4s.USPS_4State('1234987654321', '01234567891').barcodes [/code] or [code=python] from usps4s import USPS_4State print USPS_4State('1234987654321', '01234567891').barcodes [/code] | |
Re: First when you iterate over the lines, there is a newline character at the end of each line. This newline can be removed with [icode]line = line.rstrip("\r\n")[/icode]. You should write this as the first statement in the for loop. Then I suggest that you invoke an output function instead of … | |
Re: Why not [icode]pdf = open("testpdf.pdf", "rb").read()[/icode] ? | |
Re: I managed adding an element this way [code=python] from lxml import etree from lxml.builder import ElementMaker E = ElementMaker() DOC = E.doc PERSON = E.activity TITLE = E.title DESC = E.desc IDNO = E.idno def NAME(*args): return {"name":' '.join(args)} file = "xmltestthing.xml" parser = etree.XMLParser(remove_blank_text=True) # see http://codespeak.net/lxml/FAQ.html#parsing-and-serialisation thing1 = … | |
Re: Unfortunately, the os.startfile function exists only in Windows. A multiplatform way is [code=python] import subprocess as sp sp.call(["python", "textversion.py"]) [/code] Or, even better [code=python] import subprocess as sp import sys returncode = sp.call([sys.executable, "textversion.py"]) [/code] | |
![]() | Re: Also note [code=python] >>> bin(45) # python >= 3.0 '0b101101' >>> int('1110', 2) # python >= 2.5 14 [/code] Finally, see also [url=http://code.activestate.com/recipes/440528/]this link[/url]. |
Re: [QUOTE=G_S;1242407]Hi, I'm trying to make a frontend for the compile module in python. Everything works just right, except when the file has mistakes in the code that lead to a syntax error. It does raise the invalid syntax error in the terminal, but instead of executing the block inside the … | |
Re: Well, here is an example [code=python] class Thingy(object): instances = [] def __init__(self): self.instances.append(self) def waste_time_and_memory(): t = Thingy() for i in range(5): waste_time_and_memory() print Thingy.instances """ My output --> [<__main__.Thingy object at 0x7f0581777c50>, <__main__.Thingy object at 0x7f0581777c90>, <__main__.Thingy object at 0x7f0581777cd0>, <__main__.Thingy object at 0x7f0581777d10>, <__main__.Thingy object at 0x7f0581777d50>] … | |
Re: I just tested it with python 2.6 and it works. For python 3.1, I had to change the last statement to [code=python] print(int2roman(int(input("Enter an integer (1 to 4999): ")))) [/code] and it works. | |
Re: I think you should not start with a complicated gui interface. You could use simple tables like in this google code project [url]http://code.google.com/p/prettytable/[/url] to display the monthly schedule (it can generate html to view the table in your browser too). With this simple output, concentrate on the math of the … | |
Re: To test if a path is a file, you can use [code=python] import os os.path.isfile(path) # is it a file ? os.path.isdir(path) # is it a folder ? os.path.exists(path) # does it exist in the file system ? [/code] | |
Re: Since the server crashed, it displayed the exception, probably a socket.error, so use [icode]except socket.error[/icode]. In except block, put the code that you want to execute when the client disconnects in an unexpected way (it could be a simple pass statement). Also, if these lines are in a loop which … | |
Re: Perhaps you should write this at the top of your file [code=text] <?xml version="1.0" encoding="UTF-8"?> [/code] | |
Re: Because the syntax [code=python] p = [ expression ] * 3 [/code] evaluates the expression once and creates a list of 3 references to the result of this evaluation. You can use [code=python] p = [ expression for i in range(3) ] [/code] to evaluate the expression thrice and put … | |
Re: The command python alone starts an interactive interpreter in a console. You should try sendToConsole("python FILENAME.py") which executes a python program and don't enter interactive mode. | |
Re: The strange thing is not python's behavior, but your idea of initializing a base class object using the __init__ method of a subclass. The purpose of __init__ methods is to build an object, and therefore, the __init__ method of class child2 should be used to create a child2 instance. Usually … | |
Re: I once wrote a small code snippet that does this and more: [url]http://www.daniweb.com/code/snippet257449.html[/url] | |
Re: Perhaps you could read the sticky thread Starting Python [url]http://www.daniweb.com/forums/thread20774.html[/url] ! | |
Re: Apparently, it comes from a function in a file named formatting.py in xlrd source, wihch tests wether a string is a date formatting string. I think you should ignore the warning. | |
Re: This line [icode]server_socket.bind(("0.0.0.0", 5000))[/icode] looks suspicious. Normally, the address of localhost is 127.0.0.1. You should try with this address. | |
Re: An more common alternative is [code=python] >>> L = ['cmds.sphere(n = "aBall", r = 1)', 'cmds.sphere(n = "aBall", r = 2)', 'cmds.sphere(n = "aBall", r = 3)', 'cmds.sphere(n = "aBall", r = 4)', 'cmds.sphere(n = "aBall", r = 5)', 'cmds.sphere(n = "aBall", r = 6)'] >>> import cPickle as Pickle … | |
Re: If you are in a hurry to run your code, start idle, File --> New Window opens an editor window. Enter a few lines of python, then hit the F5 key : your code is running ! | |
Re: [QUOTE=G_S;1234813]Oh, wait, it's not completely solved: on linux, everything is fine. on windows, however, webbrowser.open only opens Explorer, even though firefox is the default. If I try startfile, it does open the associated program as d5e5 explained, but it fails to open the help file (it seems it only works … | |
Re: [QUOTE=tonyjv;1238985] [B]Point one[/B] You can do comparison with tuples of numbers in Python [CODE]>>> (0,0)<(1,1)<(2,2) True >>> (0,0)<(1,1)<(2,0) True >>> [/CODE] First is fine for me, but I am not agreeing with the second one. Why? If a<b<c, then number b is between a and c in the number line. … | |
Re: If you only want to catch the exception and let your code still run, you only need to write [code=python] import socket def email(): global mssg session = smtplib.SMTP(smtpserver) if authrequired: session.login(smtpuser, smtpass) try: session.sendmail(SENDER, RECIPIENTS, mssg) session.quit() except socket.error: logit('server down') [/code] Don't write [icode]except:[/icode] statements without targeting at … | |
Re: Did you learn how to write a function ? Then start writing a function to generate a single random birthday [code=python] import random def generate_birthday(): # PUT YOUR EFFORTS HERE ????? return birthday print(generate_birthday()) [/code] | |
Re: As a starting point, here is a function which computes the averages for a sequence of values (parameter A, parameter B, time). The assumption is that the input data are sorted by time. Try to run it and see if it does what you want [code=python] from itertools import groupby … | |
![]() | Re: I would use something like [code=python] from collections import defaultdict def list_has_duplicate_items(L): return len(L) > len(set(L)) def get_duplicate_items(L): D = defaultdict(int) for k in L: D[k] += 1 return [k for (k, v) in D.items() if v > 1] [/code] |
Re: I suggest to add a random number in the tuples being sorted [code=python] from random import random def test(words): t = [] for word in words: t.append((len(word), random(), word)) t.sort(reverse=True) res = [] for length, rand, word in t: res.append(word) print res test(['hello','my','friend','Peter']) [/code] | |
Re: Also, if you want to exit from a deeply nested point during the execution you can use [code=python] raise SystemExit [/code] or [code=python] import sys sys.exit(0) # use another value, like -1 to mean program failure [/code] | |
Re: The list class 'index' method performs a linear search [code=python] >>> mylist = list("hello world") >>> print(mylist) ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] >>> mylist.index('w') 6 >>> mylist[6] 'w' >>> mylist.index('z') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.index(x): … | |
Re: Here is a version which builds a single regex for all the sentences. You can add as many sentences as you whish, as long as they contain a single occurence of <mob> [code=python] # tested with python 2.6 and 3.1 import re sentences = """ You would stomp <mob> into … | |
Re: You should be able to use a dummy file by calling the linux command 'lockfile' from your programs (I never tried this, but it should work). | |
Re: An open file has a concept of 'position in the file'. After the first call to f.read(), the file position is at the end of the file. If you read again, you read an empty string. The solution is to go back to the beginning of the file [code=python] f.read() … | |
Re: The best way is to use the constructor 'int' with basis 16 to convert the hex values to integers, then use the bitwise operators &, |, ^ to perform the bitwise operations and use the 'hex' function to get the hexadecimal representation of the resulting integers. Here is an example … | |
Re: I know a method which uses the (great) [icode]lxml[/icode] module instead of ElementTree. The lxml.etree.tostring() method accepts a 'pretty_print' keyword argument. See the example here [url]http://codespeak.net/lxml/tutorial.html#serialisation[/url] . In your case [code=python] >>> from lxml import etree >>> root = etree.XML("<home><room>bedroom</room></home>") >>> print(etree.tostring(root, pretty_print=True)) <home> <room>bedroom</room> </home> [/code] | |
Re: Perhaps your file is using a BOM at the beginning. You could try open with mode 'utf-8-sig' instead of 'utf-8'. | |
Re: You can use generators to iterate over your web page's lines [code=python] URL_TEMPLATE = ... def gen_lines(symbol, stat): url = URL_TEMPLATE % (symbol, stat) for line in urllib.urlopen(url): yield line.strip() def gen_rows(symbol, stat): for line in gen_lines(symbol, stat): row = line.split(",") row = [ x.strip('"') for x in row ] … | |
Re: In linux, windows shares must be mounted. For example at home, I mount the (shared) C drive of another computer with IP address 192.168.2.4 like this [code=text] $ sudo mount -t cifs 192.168.2.4:C -o password="" /mnt/othercomp [/code] I can then access /mnt/othercomp like any other directory. I can also unmount … | |
Re: You can use the string's 'startswith' method [code=python] cnt_char = 0 log_file = open("/tmp/new.txt") for lineno, line in enumerate(log_file): # lineno starts from 0 if line.startswith("#"): continue cnt_char += len(line) if cnt_char >= 1000: cnt_char -= len(line) break print("The first %d lines contain %d characters" % (lineno, cnt_char)) [/code] This … | |
Re: I suggest a subprocess, like this [code=python] from subprocess import Popen, PIPE tethereal = Popen('tethereal -i any "port 9060"', shell=True, stdout=PIPE) while True: data = tethereal.stdout.read(1024) if data == '': break print data [/code] | |
Re: Try [icode]print repr(text)[/icode] to see what the string 'text' actually contains. Also if your file contains non ascii data, you should try the "rb" opening mode. | |
Re: You can use the [b]unidecode[/b] module available from here [url]http://pypi.python.org/pypi[/url] . For example [code=python] >>> str = unichr(int('00A9', 16)) >>> str u'\xa9' >>> from unidecode import unidecode >>> unidecode(str) '(c)' [/code] Also, you should not use 'str' as a variable name because it's the name of a builtin type. |
The End.