2,646 Posted Topics

Member Avatar for np complete

Use the [subprocess module](http://docs.python.org/3/library/subprocess.html#replacing-the-os-spawn-family) instead, as described in the documentation.

Member Avatar for Gribouillis
0
227
Member Avatar for vegaseat

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 …

Member Avatar for BearofNH
1
2K
Member Avatar for dilita.mido
Re: sd

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.

Member Avatar for james.lu.75491856
0
184
Member Avatar for 3e0jUn

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()`

Member Avatar for james.lu.75491856
0
433
Member Avatar for lewashby

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.

Member Avatar for james.lu.75491856
0
225
Member Avatar for james.lu.75491856

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.

Member Avatar for Gribouillis
0
204
Member Avatar for lewashby
Member Avatar for james.lu.75491856

> impossible.I usedmsg.as_string() The error is in the call to `msg.as_string()`

Member Avatar for Gribouillis
0
3K
Member Avatar for james.lu.75491856

TemporaryFile is not a class. Use aggregation class Var(object): def __init__(self): self._file = tempfile.TemporaryFile()

Member Avatar for Gribouillis
0
1K
Member Avatar for DeadH34d

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 …

Member Avatar for Gribouillis
0
409
Member Avatar for 3e0jUn

[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.

Member Avatar for Gribouillis
0
516
Member Avatar for frenchfrog

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).

Member Avatar for Gribouillis
0
2K
Member Avatar for SnehalBPatil

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]

Member Avatar for Gribouillis
0
2K
Member Avatar for entropic3105

$ 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)

Member Avatar for entropic3105
0
136
Member Avatar for clouds_n_things

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!

Member Avatar for clouds_n_things
1
314
Member Avatar for Ismatus3

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.

Member Avatar for Gribouillis
0
266
Member Avatar for dilita.mido
Member Avatar for Gribouillis
-2
246
Member Avatar for Ismatus3

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.

Member Avatar for Ismatus3
0
5K
Member Avatar for nutrion

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 …

Member Avatar for Gribouillis
0
208
Member Avatar for robotakid

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

Member Avatar for Gribouillis
0
729
Member Avatar for epicSHOOTER236

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']

Member Avatar for epicSHOOTER236
0
281
Member Avatar for alienwave

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.

Member Avatar for alienwave
0
146
Member Avatar for pythonforlife

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 …

Member Avatar for Gribouillis
0
284
Member Avatar for james.lu.75491856
Member Avatar for james.lu.75491856
0
143
Member Avatar for james.lu.75491856

`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)

Member Avatar for james.lu.75491856
0
177
Member Avatar for krystosan

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)

Member Avatar for Gribouillis
0
77
Member Avatar for 26bm

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.

Member Avatar for TrustyTony
0
258
Member Avatar for imperialguy

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): …

Member Avatar for Gribouillis
0
405
Member Avatar for Benkku

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.

Member Avatar for Gribouillis
0
441
Member Avatar for fatalaccidents

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 …

Member Avatar for biry2009
0
598
Member Avatar for Varunkrishna

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)))

Member Avatar for Varunkrishna
0
1K
Member Avatar for Varunkrishna

`askopenfile()` is supposed to return a file object. See `askopenfilename()` and check the value it returns.

Member Avatar for Gribouillis
0
401
Member Avatar for vivsshake

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 …

Member Avatar for vivsshake
0
351
Member Avatar for clouds_n_things

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().

Member Avatar for clouds_n_things
0
250
Member Avatar for Zingb

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.

Member Avatar for Gribouillis
0
199
Member Avatar for tony75

> 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.

Member Avatar for tony75
0
663
Member Avatar for krystosan

[Use this snippet](http://www.daniweb.com/software-development/python/code/257449/a-command-class-to-run-shell-commands)

Member Avatar for krystosan
0
335
Member Avatar for krystosan
Member Avatar for dirtydit27

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 …

Member Avatar for dirtydit27
0
242
Member Avatar for delta_frost
Member Avatar for Fernando_1

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() …

Member Avatar for woooee
0
314
Member Avatar for dirtydit27

> 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 …

Member Avatar for dirtydit27
0
466
Member Avatar for karenhaha

SyntaxError with print often means that you are running in python 3 code written for python 2.

Member Avatar for karenhaha
0
271
Member Avatar for entropic3105

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 …

Member Avatar for entropic3105
0
185
Member Avatar for paulmal

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 …

Member Avatar for Gribouillis
0
142
Member Avatar for ajit.nayak3

[This post](http://www.daniweb.com/software-development/python/threads/443909/learning-re-module#post1912119) shows how to read a csv file.

Member Avatar for bumsfeld
0
318
Member Avatar for krystosan

Start with Doug Hellmann's [PyMOTW](http://pymotw.com/2/unittest/index.html#module-unittest) about unittest.

Member Avatar for Gribouillis
0
95
Member Avatar for jeremywduncan

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 …

Member Avatar for jeremywduncan
0
431
Member Avatar for otto531

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]

Member Avatar for bumsfeld
0
312
Member Avatar for johans22

This module [http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html](http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html) perhaps ?

Member Avatar for johans22
0
161

The End.