2,646 Posted Topics
Re: Use the [subprocess module](http://docs.python.org/3/library/subprocess.html#replacing-the-os-spawn-family) instead, as described in the documentation. | |
Re: Hm. I have an old regex in my files which handles also the exponential part import re _fregex = re.compile(r"^[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$") def is_floating(f): return bool(_fregex.match(f.strip())) if __name__ == '__main__': for f in ('123','-123.45', '+3.14', '+3.', '+.3', '$99.95', '.', '2.4.3', '++2.4.3','2.4+'): print('%s => %s' % (f, is_floating(f))) """ 123 => True … | |
Re: The trick is to use the [is-a relationship](http://en.wikipedia.org/wiki/Is-a). For example "a cat *is a* mammal" implies that class Cat is a subclass of class Mammal. In practice of course, there are other possible designs. | |
Re: Replace `[user]` by `"user":{` and `[/user]` by `},`. In the same way, replace `[name]` with `"name":"` and `[/name]` with `",`. Do this with all the tags, then call `eval()` | |
Re: I wrote a linux-like [chmod() code snippet](http://www.daniweb.com/software-development/python/code/243659/change-file-permissions-symbolically-linux) once. It contains a function get_mode_by_ls() in the example part. The snippet uses the `S_*` constants of the `stat` module. | |
Re: How would you phrase the command line if you had to launch the program from a terminal ? This is the command line to use for your call. Also rrashkin is right in recommending the subprocess module. I recommend my [snippet](http://www.daniweb.com/software-development/python/code/257449/a-command-class-to-run-shell-commands) to run the command in a comfortable way. | |
Re: str.count() example: >>> "abracadabra".count("ab") 2 >>> | |
Re: > impossible.I usedmsg.as_string() The error is in the call to `msg.as_string()` | |
Re: TemporaryFile is not a class. Use aggregation class Var(object): def __init__(self): self._file = tempfile.TemporaryFile() | |
Re: First, every value in python is either True or False in a "boolean context". A boolean context occurs in "if", "while" or other statements if myvalue: # <-- boolean context. print("value was true") else: print("value was false") The expression bool(myvalue) is either True or False and this tells us whether … | |
Re: [This thread](http://www.daniweb.com/software-development/python/threads/137562/subprocess-stdout-readline-block) may help you, especially the linux solution with the socket pair. | |
Re: The first thing to check is what happens when you run the command /Applications/MATLAB_R2012b.app/bin/matlab -r "cd(fullfile('/Users/Jules/Dropbox/CODES/Matlab/')), coverGUI_AL_FOV" in an ordinary terminal (without python). | |
Re: The way you wrote your command, an argument [icode]shell = True[/icode] is necessary in Popen(). See also this snippet [url]http://www.daniweb.com/software-development/python/code/257449[/url] | |
Re: $ pydoc sum Help on built-in function sum in module __builtin__: sum(...) sum(sequence[, start]) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, returns start. (END) | |
Re: Given the menu-based structure of your program, you may find some reusable ideas in [this snippet](http://www.daniweb.com/software-development/python/code/217215/a-class-for-menu-based-terminal-applications) that I wrote a long time ago to help menu based scripts writers! | |
Re: According to [this answer](http://stackoverflow.com/questions/7071166/print-the-actual-query-mysqldb-runs), you could catch the exception and try print( repr(curso1._last_executed) ) to see which actual query was run. | |
| |
Re: I think PY_VAR4 is the TCL name of your StringVar. Try to use `modelidvar.get()` at line 46. Also the % operator is not the prefered way to substitute values in SQL statements. | |
Re: Write your own parser ! #!/usr/bin/env python import sys def handle_args(args): s = False for a in args: if a == '-s': if s: break else: s = True else: yield (s, a) s = False if s: raise RuntimeError('missing argument for -s') for item in handle_args(sys.argv[1:]): print(item) '''my output … | |
Re: You can use datetime >>> import datetime as dt >>> >>> start = dt.datetime.now() >>> start datetime.datetime(2013, 7, 16, 0, 21, 17, 748591) >>> # drink some cofee ... >>> death_date = dt.datetime.now() >>> elapsed = death_date - start >>> elapsed datetime.timedelta(0, 81, 872052) >>> elapsed.total_seconds() 81.872052 | |
Re: If the searched text is in a single line, you can read the file line by line: import itertools as itt def wrong_line(line): return 'card 1:' not in line with open('filename.txt') as ifh: result = list(itt.islice(itt.dropwhile(wrong_line, ifh), 1, 3)) # result should be the list [' ball\n', ' red\n'] | |
Re: It looks like homework. Both functions show how to compute and return a list, each of them using a different style (list comprehension vs appending list items one by one in a loop). What you can do is rewrite `computeVoltages()` using the style of `computeTimeValues()` and vice versa. | |
Re: Here is a (python 2) function to help you. It takes an open input file as argument together with an input chunk size and an output chunk size. It generates a sequence of pairs (i, s) where i is the index of the output file where the string s must … | |
Re: I'm not sure I understand which problem you are addressing with this code ... | |
Re: `random.sample()` returns a list. Try this notdone = [tuple((x,y))for x in range(5) for y in range(6)] from functools import partial s = partial(random.choice, notdone) | |
Re: A service (or daemon in other OSes) is a particular kind of process. See [windows service](https://en.wikipedia.org/wiki/Windows_service) and [daemon (computing)](https://en.wikipedia.org/wiki/Daemon_%28computing%29) | |
Re: It is possible for global variables >>> varname = 'thevalue' >>> globals()[varname] = 3.14 >>> thevalue 3.14 In principle it doesn't work for local variables. Dictionaries returned by `locals()` are read-only. | |
Re: I suggest something along the lines of from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base class SampleMeta(DeclarativeMeta): def __init__(cls, name, bases, attrs): # this is __init__ ! attrs.update({ 'id': Column('Id', Integer, primary_key=True), 'name': Column('Name', String), 'description': Column('Description', String), 'is_active': Column('IsActive', Boolean) }) DeclarativeMeta.__init__(cls, name, bases, attrs) Base = declarative_base(metaclass = SampleMeta) class Sample(Base): … | |
Re: In your example, `x == y == -1.0`. The vector `(-1.0, -1.0)` makes an angle of `-135.0` degrees with the horizontal axis, and not `45.0` degrees. So `math.atan2()` is correct. | |
Re: The python development files may be missing in your system. Usually in linux, there is a 'python' package and a 'python devel' package (on my mandriva it's 'lib64python2.6-devel'). The devel package contains header files and libraries typically used by C programs which interact with python. So, try to find the … | |
Re: You can try to sort the words by decreasing length in the regex L = sorted(Dic_Word, key = len, reverse = True) rc = re.compile('|'.join(map(re.escape, L))) | |
Re: `askopenfile()` is supposed to return a file object. See `askopenfilename()` and check the value it returns. | |
Re: The memory error came probably from minidom trying to build a whole dom tree in memory. This has nothing to do with the way the file is read. I think a good solution is to use a SAX parser, which doesn't store a tree. It is very easy to do: write … | |
Re: If no line of /Users/some_user/Desktop/passwords.txt contains a colon, your program won't print any output. Add a call to print() for every line in the loop. Edit: I just noticed the call to readline(). It reads only a single line. Use readlines(). | |
Re: There are ready-made Ordinary Differential Equation solvers and modules in python, you could start with the module scipy.integrate. I don't understand the equation you wrote above, nor in which sense it is an ODE, Perhaps you could give us more details about your problem and your equation. | |
Re: > Please why I get this error when I run my code? Don't call your file crypt.py if it is importing a module named crypt. Remove any file crypt.py or crypt.pyc from your folder. | |
Re: [Use this snippet](http://www.daniweb.com/software-development/python/code/257449/a-command-class-to-run-shell-commands) | |
Re: Did you try `nargs = '*'` ? | |
Re: It is already efficient (1.6 microseconds on my computer) >>> from timeit import Timer >>> L = [1,2,3,4,5,6,7,8,9,10] >>> # run your statement 1 million times >>> Timer("sum([(i) for i in L if i%2 ==0])", "from __main__ import L").timeit() 1.607414960861206 >>> # removing the inner list construction is surprisingly less … | |
Re: Please use the Code button in the forum's editor to post your code # VARIABLE DEFINITIONs currentName = "" course = "" grade = "" categoryTotal = 0 eof = False grandTotal=0 gradeFile = "" #----------------------------------------------------------------------- # CONSTANT DEFINITIONS #----------------------------------------------------------------------- # FUNCTION DEFINITIONS def startUp(): global gradeFile,currentName,previousName,course,grade,eof print ("grade report\n").center(60).upper() … | |
Re: > I'm trying to make the code general as possible so that any csv file and column index can be used. There is some work if you want to reach this universality. Csv files may vary on their encoding, their quoting strategy, their separator. See the csv module's documentation, especially … | |
Re: SyntaxError with print often means that you are running in python 3 code written for python 2. | |
Re: You can download one [here](http://sourceforge.net/p/pydrawing/home/pydrawing/), called pydrawing, which claims to draw diagrams in a tkinter canvas. Python and tkinter have been around for 20 years, which means many attempts to write paint programs. There is a basic example in Mark Lutz' book 'programming python'. The first step in your project … | |
Re: I suggest a recursive search where allocated matches are represented by a list of lists F = [ [(0, 1), (2, 4), (3, 6)], [(2, 3), (0, 7)], [(4, 5), (1, 6)], [(6, 7), (3, 5)] ] There are 4 rows in this list, each representing a field. Here, F … | |
Re: [This post](http://www.daniweb.com/software-development/python/threads/443909/learning-re-module#post1912119) shows how to read a csv file. | |
Re: Start with Doug Hellmann's [PyMOTW](http://pymotw.com/2/unittest/index.html#module-unittest) about unittest. | |
Re: Use the Command class in [this code snippet](http://www.daniweb.com/software-development/python/code/257449/a-command-class-to-run-shell-commands) to get your shell command's output com = Command(zip_command).run() print(com.output) print(com.error) if com.failed: print('BACKUP FAILED!') else: print('Successful backup to ' + target) `os.system()` is deprecated in favor of the `subprocess` module. You may also consider using module `zipfile` instead of an external … | |
Re: Use dictionaries D = [dict(zip(*WordsFrequencies(name))) for name in ['file1.txt', 'file2.txt']] common_words = set(D[0]) & set(D[1]) L = [(w, D[0][w] + D[1][w]) for w in common_words] # sort by decreasing frequencies, solve ties by increasing alphabetical order. L.sort(key = lambda t: (-t[1], t[0])) L = L[:20] | |
Re: This module [http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html](http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html) perhaps ? |
The End.