Try to open a terminal and type
locate Python.h
If you don't have the locate command, install it. You may have to update the locate database. See here for example.
Try to open a terminal and type
locate Python.h
If you don't have the locate command, install it. You may have to update the locate database. See here for example.
I don't use macosx, but don't you miss some python development headers ? For example can you locate the file Python.h
?
I suggest this if module games.food
contains function food()
, etc
from importlib import import_module
import games # games package has all modules to be used. The modules include color, food etc
GAMES = ('color', 'food', 'car', 'toy')
while True:
question = input('Please enter your question: ').lower()
if not question:
break
for g in GAMES:
if g in question:
module = import_module('games.' + g)
getattr(module, g)()
break
else:
print('I do not have a game for that! :(')
print('Byebye!')
It seem that you have the same problem as Maurice_3, and maybe the same teacher :)
I don't know how you launch the program from notepad++, but if you can invoke python with option -i, it should prevent the cmd from closing.
Apparently, the stream sys.stdin
was closed when your program attempted to read a line. In which context did you run the program ? Which OS first ? was it in a python IDE ? was it in a terminal ? Did you type a CTRL D in a terminal while running the program ? Was the program called from another program ?
I could not explain this better than the python documentation. An advantage of printing the repr of a string is that you can see the non printable characters contained in the string. For example a newline character is represented as \n
.
After line 3, add
print(repr(password))
print(repr(userguess))
then you can compare visually the two strings.
Normally, you can't do that and you should not be doing that. However this is python and most things happen to be possible. A trick is to replace the module in sys.modules
by a pseudo module object with the same dict and a __call__()
method. Here is module lemodule.py
in python 2.7:
# -*- coding: utf-8 -*-
"""
lemodule.py
"""
if __name__ != '__main__':
import sys
class PseudoModule(object):
def __init__(self, dic):
self.__dict__ = dic
def __call__(self):
return 3.14159
sys.modules[__name__] = PseudoModule(
sys.modules[__name__].__dict__)
Now here is the program main.py which does what you want
# -*- coding: utf-8 -*-
"""
main.py
"""
import lemodule
var = lemodule()
print(var)
"""my output -->
3.14159
"""
Try
sql = ("SELECT * FROM `emaillogs`"
" WHERE `id` BETWEEN {i1:d} AND {i2:d}"
" ORDER BY `id` DESC").format(
i1 = int(limit1), # type checking with conversion
i2 = int(limit2),
)
It seems that you must use the LIMIT keyword in the SELECT statement, as described in the mysql documentation. For example
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
See also this. I dont know how it will interact with your ORDER BY clause.
Then I must have missed something. I don't have the sublime editor to test your code unfortunately.
I don't see how you can receive input from an external editor using subprocess.Popen()
since the external editor does not usually send user input to the outside world (via stdout or a socket, ...).
An exception to this is when the editor saves the file being edited. This changes the modification time of a file on disk, and this event can be intercepted by modules watching files or directory (such as pyinotify or perhaps QtCore.QFileSystemWatcher). Your program could then read the file on disk.
Another way is to see if there is a plugin for your editor which can send the contents of the editor window to a socket or a pipe.
I think you are trying to do something completely impossible. The first argument in Popen() must be a valid command line (either a string or a list, see the doc) which you could write in a terminal and execute. You can't write
open(os.path.join(os.getcwd(), "foo.txt") "w")
in a terminal and expect a pleasant answer from your computer.
If you want to read from an editor window in your python program, the normal way to go is to use one of the GUI frameworks.
As always, your code violates every rule of good design. It is possible, in theory, with a statement such as
C.__class__ = B
However you may find more help if you post the code of bu32, deref, bu() etc.
I suggest that you translate wikipedia's pseudo-code into python. It looks like 20 lines of code ...
Replace last line with
words[:] = [word for count, word in vow_count]
This will replace the contents of list 'words' by your result. Also the line count = 0 should be inside the for loop. Print the result at the end of your function to see what happens.
One thing is clear: the __new__()
method is not the place where this should be implemented. The role of the __new__()
method is to create an instance before this instance is initialized. Normally, you don't need to use it unless you subclass a builtin type or you are playing with metaclasses.
As a simple solution, I suggest to turn your methods into instance methods and add a method keyword to the constructor. Client code could use
p = Polygon(method = "from-center", center = (0, 0), length = 3)
then
class Foo(object):
def __init__(self, *args, **kwargs):
method = self._guess_method(args, kwargs)
if method == 'from-a':
self.init_from_a(*args, **kwargs)
elif method == 'default':
self.init_default(*args, **kwargs)
else:
raise ValueError(('Unknown method value for Foo', method))
def _guess_method(self, args, kwargs):
try:
return kwargs['method']
except KeyError:
pass
if 'a' in kwargs:
return 'from-a'
else:
return 'default'
def init_from_a(self, *args, **kwargs):
print 'initializing "from_a()"'
def init_default(self, *args, **kwargs):
print 'Foo default initializer'
if __name__ == '__main__':
Foo(method = 'from-a', a = 2)
Foo(a = 3)
Foo(5, 6, bar = 'baz')
Another nice thing is that you can still define later
from functools import partial
polygon_from_center = partial(Polygon, method = 'from-center')
It seems to me that all this is very flexible and pythonic.
Try PyInstaller perhaps. Notice that most linux distributions ship with python 2 or 3 installed or both, or the other one can be installed with a few keystrokes, so I don't think a stand alone executable is very useful.
Hm, a few visible issues:
f2.write(match.group(0))
(or 1 depending on what you want)re.findall(r'...' ...)
. Raw strings preserve backslashes, and this is what the regex parser needs.Obviously you don't understand what the code does. Try
import os
import sys
import time
import ImageGrab
import Image
from os import environ
import random
n = -1
while True:
n += 1
# generate a random time between 120 and 300 sec
random_time = random.randrange(120,300)
# wait between 120 and 300 seconds (or between 2 and 5 minutes)
print "Next picture in: %.2f minutes" % (float(random_time) / 60)
time.sleep(random_time)
img = ImageGrab.grab()
FILES_DIR = 'pic'
SAVE_PATH = os.path.join(environ['HOMEDRIVE'], environ['HOMEPATH'])
#SAVE_PATH = os.path.expanduser("~") #It is cross-platform
LOGFILE_NAME = "test{n:0>5}.png".format(n = n)
LOGFILE_PATH = os.path.join(SAVE_PATH, FILES_DIR, LOGFILE_NAME)
img.save(LOGFILE_PATH)
Use a variable name
for n in range(10):
LOGFILE_NAME = "test{n:0>5}.png".format(n = n)
print(LOGFILE_NAME)
"""my output -->
test00000.png
test00001.png
test00002.png
test00003.png
test00004.png
test00005.png
test00006.png
test00007.png
test00008.png
test00009.png
"""
I think it should be img.save(LOGFILE_PATH)
The home directory is best obtained with
home_dir = os.path.expanduser("~")
It is cross-platform !
Save as test.jpg
.
I didn't say import matplotlib
but import pyparsing
Where is pyparsing.py on your computer ?
What does python say when you type import pyparsing
?
Did you install pyparsing ?
If it's still the same error message, it means that your python cannot find the pyparsing module and you must find out why. Try
>>> import pyparsing
in your interpreter. Also try to locate pyparsing.py on your computer.
I tried to reproduce the bug in windows XP with python 32 bits installed. I had to install python-dateutil module from Christoph Gohlke's site, then pyparsing as I said in the previous post, but the installer refused to run because I didn't have msvcr71.dll. I got the dll here (download the zip file uncompress and move the dll to the System folder). Once pyparsing was installed, I needed numpy (1.8.0 superpack from sourceforge) and finally the package Six from Gohlke's site. Then the following line succeeded
from matplotlib import pyplot as plt
My advice: install linux mint in a virtualbox and say good bye to issues in python modules installs !
I agree with vegaseat, try
import tkinter
print(tkinter)
Perhaps replace host
with host.get()
in lambda
.
The best thing to do is raise the exception to see what happened:
except:
print 'Error. Try again'
raise
The drawback of except is that it hides exceptions !
Also notice that there are many results if you search the word 'magic' in pypi, (without k) especially python implementations of 'file', python bindings to the libmagic library, even packages like python-magic apparently work in windows with the GnuWin32 package.
Of course, all this may be overkill for your program.
Don't use sleep()
in gui programs. Use a timer instead (method after()
in tkinter). Run this example by PyTony to see how it works.
You can shorten the tests
from graphics import *
def patchdrawer():
win = GraphWin("Patch drawer", 100, 100)
for x in range(0, 5):
for y in range(1, 6):
p1 = Point(x * 20, (y - 1) * 20)
p2 = Point((x + 1) * 20, y * 20)
rectangle = Rectangle(p1, p2)
rectangle.setFill("red" if (x + y) % 2 else "white")
rectangle.draw(win)
for x in range(0, 10):
for y in range(0, 10):
centre = Point(((x + 1) * 10) - 5 , ((y + 1) * 10) - 5)
circle = Circle(centre, 5)
circle.setFill("white" if (x % 4) // 2 == (y % 4) // 2 else "red")
circle.draw(win)
win.getMouse()
win.close()
if __name__ == "__main__":
patchdrawer()
I disapprove inflammatory debates in daniweb. I had one once with a knowledgeable programmer and some time later, he ceased to connect. I think he had too strong convictions and he wanted everybody to agree.
Every gui problem has already been solved by vegaseat. Type tkinter bargraph
in daniweb's search form and you'll find many examples, like this one, still fully working after 7 years !
Perhaps convert to dict first
def main(args):
f = open(args[1], 'w')
inp = raw_input("Enter a Dict")
# inp = {"a":1,"b":2}
inp = django.utils.simplejson.loads(inp)
assert isinstance(inp, dict)
django.utils.simplejson.dumps(inp, f)
Partial does currying:
>>> from functools import partial
>>>
>>> def FOO(x, y, z):
... print((x, y, z))
...
>>> BAR = partial(FOO, "baz", "qux")
>>> BAR(3.14)
('baz', 'qux', 3.14)
BAR is the same function as FOO, but it takes only one argument (the last argument). The 2 first arguments have been set to fixed values "baz" and "qux".
The obvious error is that the file argument in storbinary() must be an open file object instead of a string. Try
with open(sourcepath, 'rb') as ifh:
ftps.storbinary(outbound, ifh, 8192)
Yes, you are new to python, but not to programming. Here is a simpler snippet to create an adjacency dictionary
dicfile = ...
def dist(word, other):
return sum(1 if (x == y) else 0 for (x, y) in zip(word, other))
def all_items():
for i, word in enumerate(dicfile):
for other in dicfile[i+1:]:
if dist(word, other) == 3:
yield (word, other)
yield (other, word)
if __name__ == '__main__':
from collections import defaultdict
from pprint import pprint
D = defaultdict(set)
for k, v in all_items():
D[k].add(v)
D = dict(D)
pprint(D)
""" my output:
{'ante': set(['ants']),
'ants': set(['ante']),
'calf': set(['call', 'calm']),
'call': set(['calf', 'calm', 'mall', 'tall']),
'calm': set(['calf', 'call']),
'dire': set(['sire', 'tire']),
'edit': set(['emit']),
'emit': set(['edit']),
'fail': set(['rail']),
'fate': set(['late', 'mate', 'pate', 'rate']),
'feat': set(['meat', 'neat', 'peat']),
...
"""
Here is the graph, generated with this code snippet and a few more lines:
from fastgraph import graph
dicfile = ["ante", "ants", "calf", "call", "calm", "clam", "diet", "dire", "earl", "edit",
"emit", "erst", "fail", "fate", "feat", "feta", "ires", "irks", "item", "lair",
"lame", "late", "leap", "les", "lets", "liar", "lips", "lira","list", "lite",
"male", "mall", "mate", "matt", "meal", "meat", "mint", "mite", "mitt", "naps",
"neat", "nips", "nite", "nits", "opts", "pale", "pans", "past", "pate", "pats",
"peal", "peat", "pest", "pets", "pier", "pins", "pits", "plea", "post", "pots",
"rail", "rant", "rate", "real", "rest", "rial", "ride", "ripe", "rise", "risk",
"rite", "rite", "shin", "silt", "sire", "slip", "slit", "snap", "snip", "snit",
"span", "spat", "spin", "spit", "spot", "step", "stop", "tale", "tall", "tame",
"tans", "tape", "taps", "tare", "tarn", "teal", "team", "tear", "tide", "tied",
"tier", "tier", "tile", "time", "tine", "tins", "tint", "tips", "tire", "tire",
"tops", "lisp"]
def dist(word, other):
return sum([1 if (x == y) else 0 for (x, y) in zip(word, other)])
def all_items():
for i, word in enumerate(dicfile):
for other in dicfile[i+1:]:
if dist(word, other) == 3:
yield (word, other)
if __name__ == '__main__':
def label(x):
return x
g = graph(all_items(), label)
g.draw('dicfile.png', prog='fdp') # prog can be neato|dot|twopi|circo|fdp|nop
The 4 letters words are nodes in a graph where adjacent nodes differ by one letter from the current node. Starting from the startword, you can do a depth first walk of the graph until you reach the endword. I posted a clue for depth first traversal here (replace urls with 4 letter words).
You must try some python code. We already gave 2 methods, where is your python code to extract the data ?