2,646 Posted Topics
Re: > python -i tinyscrip.py I don't use komodo, but apparently you are typing in a python shell a command which should be typed in a terminal. | |
Re: > What is cms detector? It seems that cms detector means [Compact Muon Solenoid](http://ireswww.in2p3.fr/ires/recherche/cms/stephanie/CMSdetectE.html). | |
Re: You can't double the double quotes like this >>> r"<option value=""([a-zA-Z])"">[�-9; a-zA-Z()]</option>" # bad '<option value=([a-zA-Z])>[�-9; a-zA-Z()]</option>' >>> r'<option value="([a-zA-Z])">[�-9; a-zA-Z()]</option>' # good '<option value="([a-zA-Z])">[�-9; a-zA-Z()]</option>' Use [kodos](http://kodos.sourceforge.net/) to debug regexes. edit: in python, `r"foo""bar""baz"` is the same as `r"foo" + "bar" + "baz"`. | |
Re: Perhaps you're taking the square root of a negative number ? Also your formulas are false. Why not introduce a variable [icode]delta = b * b - 4 * a * c[/icode] to clean up the code ? | |
Re: Vegaseat wrote [this great example](http://www.daniweb.com/software-development/python/code/216484/wxpython-listbox-demo) 7 years ago, and it still works out of the (list) box ! | |
![]() | Re: It's not very useful. You could `del time` to remove the name time from the current namespace, but it would not *unimport* the module. The module is still in `sys.modules['time']`. You could `del sys.modules[module.__name__]`, but it would not *really* unimport it as other modules may keep a reference to the … |
Re: In python, a file opened for reading supports the 'iterable protocol', it means that it can behave like a sequence of items, each item being a line of the file. For example it could be transformed into a list of lines L = list(open('spam.txt')) It can also be used in … | |
Re: I don't know how glade works, but I recently hand coded a GtkListStore, and I remember that the method treeview.add_column() must be called on each column that you want to see to correctly initialize the treeview. Can you check this in your code ? edit: sorry, it's append_column() | |
Re: I found a simple way to load or reload a firefox tab from python which uses a firefox addon called 'remote control'. Using this add-on in a single firefox tab, your python program can change automatically the browser's page content. [See this snippet](http://www.daniweb.com/software-development/python/code/410101/load-reload-a-firefox-tab-from-python). There is also [this module](http://code.google.com/p/python-browsercontrol/) but I … | |
Re: There is also numpy.loadtxt() to read the file import numpy with open("numfile.txt") as ifh: arr = numpy.loadtxt(ifh, usecols = (2, 3), dtype=float, delimiter=" , ", skiprows = 2) print arr """ my output --> [[ 2.00000000e+00 -1.00000000e-04] [ 2.00000000e+00 1.69973300e-01] [ 2.00000000e+00 3.36706700e-01] [ 2.00000000e+00 5.00040000e-01]] """ Use matplotlib to … | |
Re: Perhaps you could upload the element using this function import pickle import zipfile def save(obj): s = pickle.dumps(obj, 0) with zipfile.ZipFile('spam.zip', 'w') as myzip: myzip.writestr("elt", s) save(element) then attach the file spam.zip to a post, so that we can read it and study the element. You must also tell us … | |
Re: A script is a python program like ex1.py (actually a script is a program in some scripting language, like python, perl, sh, etc). [b]Google[/b] says that an octothorpe is the '#' symbol. | |
Re: There are gui builders for wxpython, pyqt and pygtk, I suggest that you start with this list of tools http://wiki.python.org/moin/GuiProgramming . I read good reports about pythoncard for example. See here http://pythoncard.sourceforge.net/walkthrough2.html | |
![]() | Re: In linux, you can clear the screen with def clear(): print("\x1B[2J") clear() This uses the ANSI escape sequences which work in a linux terminal. This may work in windows too if you import module colorama which implements ansi sequences for all OSes from colorama import init init() it will also … |
Re: Download and install module xlrd (`pip install xlrd`) and type xlrd in this forum's search box. | |
Re: You could use a small web server like [bottle](http://bottlepy.org/docs/dev/#). The server side is almost trivial (define a function to serve [static files](http://bottlepy.org/docs/dev/tutorial.html#routing-static-files)), the client side is straightforward using module urllib. Your app could start/stop the server process and manage the content of the directory where it would store the static … | |
![]() | Re: You must learn to read the python documentation. `getpass.getpass([prompt[stream]])` in the documentation's notations means that you can call getpass one of the following ways getpass.getpass() getpass.getpass(prompt) getpass.getpass(prompt, stream) prompt is a string, and stream is a file object. |
Re: You can try this too import os p = os.path.join('C:\', 'Users', 'spreston', 'Desktop', 'HeadFirst', 'Chapter 3') | |
Re: You could first work with file A alone and create a dictionary having the structure { 1: { '123456':'england', '234564': 'brazil', '939311': 'germany', }, 2: { '213213':'italy', }, 500: { '74778': 'denmark', }, } then work with file B and this dictionary. | |
Re: Here is a stronger code to read the number from user input. def findx(): # This function asks an integer from the user, it does not need a parameter. while True: # This means 'repeat indefinitely' (unless a break or return or raise statement is met) try: z = int(input("Enter: … | |
Re: The road to writing "good programs" is paved with writing hundreds of not so good programs. The most important step is that your programs run :) | |
Re: > What I do need in my database import file is the first part of the textfile containing the 'sort of' columns but is a bit distorted with spaces etc... Perhaps you could describe with words the precise way the lines are 'distorted'. If it can't be described precisely, it … | |
Re: The standard library contains the method `getpass.getuser()` to get the user name, and there is also `os.path.expanduser('~')` to get the home folder. On my unix system, there is no `USERPROFILE` environment variable for example. | |
Re: There is also my_string[:my_string.index('.') + 3] or "{0:.2f}".format(float(my_string)) but the program no longer illustrates the split() method. | |
![]() | Re: In python 2, there is no difference between print "foo" print ("foo") because print is a statement and the expression `("foo")` has the same value as the expression `"foo"`. On the other hand the statements print "foo", "bar" print ("foo", "bar") are **not** equivalent because `("foo", "bar")` is a single … |
Re: Adding a call to select.select() with a timeout works for me import select import sys import termios class TimeoutError(Exception): pass TERMIOS = termios def getkey(): fd = sys.stdin.fileno() old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO new[6][TERMIOS.VMIN] = 1 new[6][TERMIOS.VTIME] = 0 termios.tcsetattr(fd, TERMIOS.TCSANOW, new) … | |
Re: You can try something like this #!/usr/bin/env python # -*-coding: utf8-*- # Title: remcol.py # WARNING: UNTESTED import os class Error(Exception): pass def remove_column(srcdir, dstdir = None): if dstdir is None: dstdir = os.path.join(os.path.expanduser("~"), "columnremoved") if os.path.exists(dstdir): # this guarantees that this function won't overwrite anything on the disk raise … | |
Re: Here is function to find punctuation "by hand", but I won't help you more because it's homework. [code=python] text = """In 1876 the then Duke of Marlborough was appointed Viceroy and brought his son, Lord Randolph Churchill, to reside at the Little Lodge as his Private Secretary. Lord Randolph was … | |
Re: jlm699 how can you put the tag without triggering their action ? | |
Re: You could also read the file and build a dict mapping pairs like `('Pedro', 'groceries')` to the total cost for Pedro in this category (the float 1.42). So the dictionary would look like { ('Pedro', 'groceries'): 1.42, ('Nitin', 'tobacco'): 15.0, ('Susie', 'groceries'): 10.25, ... } | |
Re: The path in the error message > Error 277 for "open "A:Chrome DownloadsJhalla_Wallah_(Remix)_-_(MusicTub.Com).mp3 looks strange. You may have to use something like path = r"A:\Chrome Downloads\Jhalla_Wallah_(Remix)_-_(MusicTub.Com).mp3" | |
Re: There is no return statement in function `fixcase()`, so that your variable `output` will always be `None`. Also have a look at the `capitalize()` string method. | |
![]() | Re: Also have a look in standard module `cmd`, and also this [code snippet](http://www.daniweb.com/software-development/python/code/258640/enhanced-cmd-class-for-command-line-interpreters). |
Re: A circle with center (a,b) and radius r has the equation `(x-a)^2 +(y-b)^2=r^2`. If the horizontal line has the equation `y = c`, it means that the intersection points are given by `(x-a)^2 = r^2 - (c-b)^2` when this is non negative, so that x = a +/- sqrt(r**2 - … | |
Re: Also '\t'.join(str(x) for x in mylist) | |
Re: I don't understand why you open the logfile in read mode in the first case. You can try the following, which should create an error file with a traceback if the logfile does not open from datetime import datetime import os import traceback logfilename = os.path.join('C:\', 'Dir1', 'Sub One', 'Sub3', … | |
Re: Also `len(word)` gives the number of letters in a word. | |
Re: It's always been like this: if you evaluate a python expression in a namespace, the `__builtins__` dictionary is inserted in that namespace. For example In [3]: D = dict() In [4]: D.keys() Out[4]: [] In [5]: eval("1+2", D) Out[5]: 3 In [6]: D.keys() Out[6]: ['__builtins__'] I think it's done at … | |
When working whith large data files, it may be desirable to output a sequence of bytes by large chunks. This snippet defines a file adapter class to handle this transparently. Writing bytes to an ChunkedOutputFile will automatically write the underlying file object by fixed length chunks. | |
Re: Yes, python is extremely permissive. Any function can call any other function in any module, including the module where it is defined. | |
Re: The path `C:\Python27\Lib\site-packages\Obspy\Lib\site-packages\obspy.core-0.6.2-py2.7.egg` looks strange. Something like `C:\Python27\Lib\site-packages\obspy.core-0.6.2-py2.7.egg` would look more conventional. Did you install obspy with a windows installer ? If you don't want to change anything, you can try to add this path `C:\Python27\Lib\site-packages\Obspy\Lib\site-packages` to your PYTHONPATH environment variable. | |
Re: I don't use SUSE linux, but can't you simply find a 'python-numpy' rpm package for your system ? Also did you check [this page](http://www.scipy.org/Installing_SciPy/Linux) ? | |
Re: Here is a way [code=python] def createData2(): L = [line.strip() for line in open("data.txt")] L = [line for line in L if line] data2 = open("data2.txt", "w") data2.write(" ".join(L)) data2.close() if __name__ == "__main__": createData2() [/code] | |
Re: In linux I used [pyinotify](https://github.com/seb-m/pyinotify) which works very well. | |
Re: Use datetime module >>> from datetime import datetime, timedelta >>> fm = "%d-%b-%y" >>> delta = timedelta(days=14) >>> d = datetime.strptime("28-FEB-12", fm) >>> (d - delta).strftime(fm) '14-Feb-12' | |
Re: Congratulations for moderatorship. Now, you're supposed to have all the solutions, so tell me, is there a way to display threads by last post first in the new system ? It was a very nice feature in the previous daniweb interface, please do something so that the administrative staff implement … | |
Re: Notice that independently from the pythonic solution above, one can use imagemagick on the command line, it's a specialized tool to convert between image formats. Here is a working command once imagemagick is installed convert temp.png temp.bmp This command has many options to manipulate size, color, transparency, etc. | |
Re: I tried to do it using itertools.groupby(), but hihe's method is faster. The reason is probably that groupby() needs an initial sort, while filling a dict doesn't. Here is the comparison #!/usr/bin/env python # -*-coding: utf8-*- # compare two implementations of creating a sorted index list data_list = ['the', 'house', … | |
This python 2 code snippet uses unicode chess symbols and box drawings symbols to display a chessboard in a terminal. With a terminal profile having a monospace font of size 20 or more, it looks quite usable to play chess. | |
Re: You can also print chess symbols in the terminal, they are small, but it works >>> print u"\u2654\u2655\u2656\u2657\u2658\u2659\u265A\u265B\u265C\u265D\u265E\u265F" ♔♕♖♗♘♙♚♛♜♝♞♟ Together with the box drawings code points (unicode 2500 +), it should be possible to draw a nice looking chessboard in a terminal. Your os will probably let you choose your … |
The End.