Note that since you're only copying the file, you should consider using shutil.copy like this
import shutil
maxValue = 20
for i in range( 1, maxValue + 1 ):
shutil.copy("filename.txt", "File%d.txt" % i )
Note that since you're only copying the file, you should consider using shutil.copy like this
import shutil
maxValue = 20
for i in range( 1, maxValue + 1 ):
shutil.copy("filename.txt", "File%d.txt" % i )
Well, super has been around for some time now, but it's not very useful. Better call the parent class directly.
You don't even need the readlines(). You can iterate on the file object directly. On the other hand, after the file has been read, the file position is at the end of the file, so you must use seek to go to the beginning of the file
initFile = open( "filename.txt", "r" )
maxValue = 20
for i in range( 1, maxValue + 1 ):
onitFile = open( "File%d.txt" % i, "w" )
initFile.seek(0) # go to the beginning of the input file
for fileLine in initFile:
onitFile.write( fileLine )
onitFile.close()
initFile.close()
You must overwrite the __setitem__ method
class mydict(dict):
def __setitem__(self, key, value):
doStuff()
return dict.__setitem__(self, key, value)
There is nothing very clever here. You must learn to think about algorithms. You want to output a series of blocks of lines; each block is indexed by the the number k in file<k>.tcl. So the structure of your algorithm is (this is pseudo code, not python)
for k in 0, 1, 2, ..., maxValue -1:
print block k
Now you must find how to print block k. You must first print a header line with the file name, and then a series of lines indexed by the number p in $traf<p>. This index goes from 0 to k, so your structure is now
for k in 0, 1, 2, ..., maxValue -1:
print header line with file<k>tcl
for p in 0, 1, ..., k:
print line with $traf<p>
All you have to do is translate this to python.
You should also read the documentation of the standard lib module atexit which gives example of how you can register functions to be executed at program termination.
I ended up figuring it out by breaking down sin into a function of series rather than using Taylor expansions. It was much simpler. This was my code for sin:
def sine(x): sum = 0.0 n = 0.0 term = 1.0 while (term > .0000000001): #loops until the iterations grow so large that 'term' becomes negligibly small term = ((x ** (2 * n + 1.0))) / (factorial(2 * n + 1.0)) if n % 2 == 0: sum += term else: sum -= term n += 1 return sum
I also had made a function to calculate factorials, fyi.
You can speed this up:
def sine(x):
term = float(x)
result = term # avoid 'sum' which is the name of a builtin function
u = - term * term # this is minus (x squared)
n = 0 # use an integer for integer data
while abs(term) > 1.0e-10:
n += 2
term *= u / (n * (n+1))
result += term
return result
The remaining question is to give an estimate for the error on the result. With this series, I think I can prove that with an n having the same order of magnitude as x (say n > 2|x|) for example, then the error on the result is smaller than 2 |term| for example. This is bad when x is large, but you can speed up things because sine is 2 pi -periodic. So a good idea would be to replace x by y = x …
I have a small collection of receipes found on the web a long time ago. See if one of them can help you
# linux, mac
os.kill(pid, signal.SIGKILL)
killedpid, stat = os.waitpid(pid, os.WNOHANG)
if killedpid == 0:
print >> sys.stderr, "ACK! PROCESS NOT KILLED?"
# windows
handle = subprocess.Popen("someprocess here", shell=False)
subprocess.Popen("taskkill /F /T /PID %i"%handle.pid , shell=True)
# also
# Create a process that won't end on its own
import subprocess
process = subprocess.Popen(['python.exe', '-c', 'while 1: pass'])
# Kill the process using pywin32
import win32api
win32api.TerminateProcess(int(process._handle), -1)
# Kill the process using ctypes
import ctypes
ctypes.windll.kernel32.TerminateProcess(int(process._handle), -1)
# Kill the proces using pywin32 and pid
import win32api
PROCESS_TERMINATE = 1
handle = win32api.OpenProcess(PROCESS_TERMINATE, False, process.pid)
win32api.TerminateProcess(handle, -1)
win32api.CloseHandle(handle)
# Kill the proces using ctypes and pid
import ctypes
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)
You probably still have the wrong indentation for the line
status = staticmethod(status).
I see. Note that handling errors by the means of a return status is not very pythonic. It's a C like way of thinking. A more pythonic approach would be to define a
class LibraryError(Exception):
pass
and in your methods, you could raise a LibraryError instead of returning False. Then client code could catch LibraryError. This gives client code the freedom to handle the error or not. If it doesn't handle it, the exception propagates.
The indentation is bad. The code should read
# Classy Critter
# Demonstrates class attributes and static methods
class Critter(object):
"""A virtual pet"""
total = 0
def status():
print "\nThe total number of critters is", Critter.total
status = staticmethod(status)
def __init__(self, name):
print "A critter has been born!"
self.name = name
Critter.total += 1
# main
print "Accessing the class attribute Critter.total:",
print Critter.total
print "\nCreating critters."
crit1 = Critter("critter 1")
crit2 = Critter("critter 2")
crit3 = Critter("critter 3")
Critter.status()
print "\nAccessing the class attribute through an object:",
print crit1.total
raw_input("\n\nPress the enter key to exit.")
About the error message: with your bad indentation, there was no __init__ method in class Critter. So the call crit1 = Critter("critter 1") passed the string argument "critter 1" to the object class, and finally to object.__new__ which creates a new object. Since python 3.0, this method does not accept any parameters but the calling class. Note that if you are using python >= 3, you must modify the print statements.
Thank you all very much for your help in the decision. I have gone with design one and have implemented the features that I want so far. I am going to create a two front ends to implement the module. One command line and the other GUI. You can view the current module at coder profile and I will be posting the finished applications with downloads very soon to coder profile.
Nice. Just one criticism, I don't like your
except:
return False
because you're just hiding errors, so that if something goes wrong, your program will never know. You should think about another way to handle the error (if you don't want to write error recovery code, you could send the error to a log file).
I prefer design 1. We don't know anything about the algorithms that you have in mind, so there is no obvious benefit for introducing the classes Search and Edit. With design 1, the Library object appears as a facade behind which you can implement arbitrary complex and flexible algorithms.
Also I don't think it's a good idea to use nested classes in general. There is no gain in nesting classes and they will be more accessible if you implement them linearly at module level.
Don't you think you could save some CPU usage if you replaced the "while 1" by a timer which would run the loop at a certain frequency ?
I found out the launcher is actually called: localhost.desktop
but if I do:os.system("~/localhost.desktop")
it just starts my standard editor and shows the script...
I don't know ubuntu very well, but if your launcher is related to a bash script, the script must be somewhere in the filesystem, so locate the script and call os.system(path_to_script)
or subprocess.Popen(["bash", path_to_script])
.
Note (so you don't waste your time): bpython uses Linux's curses and does not work with Windows.
bpython doesn't even work on my linux box. It could be the 64 bits chipset...
I've been doing some more research and testing, and I've hit a roadblock. While an object can have a reference to an imported module, it doesn't actually have its own copy of the module. Somehow Python only imports the module once, and somehow each and every agent object points directly to this module. That means modifying the variables in one agent's module modifies those variables in agent's with the same module, and reloading one agent's module reloads it for all agent's.
I know of no easy way to alter this behavior. I'm thinking I'm going to have to try to write my own importer to achieve the results I desire.
The standard pattern in python is that when you want different copies of similar things, you don't use modules but class instances. I think your agents should aggregate objects having the desired abilities instead of modules with a non standard importing policy. Another possible design is to dynamically add methods to your agents (some kind of mixin stuff).
Anyway, this is too theoretical. you should write some clear use cases for your 'agents'. There is most probably a better design for this.
I modified your code so that it prints the file name and the destination name instead of renaming the file. Run it and modifiy it until it gives the correct values, then uncomment the 'rename' line.
#!/usr/local/bin/python
import re, os
from os.path import join as pjoin, isdir
while True:
targetfolder = raw_input('enter a target folder:\n').strip()
if isdir(targetfolder):
break
else:
print("you must enter an existing folder!")
newname = raw_input('enter a new base name:\n').strip()
newname = pjoin(targetfolder, newname)
rxin = raw_input('enter a regex to search for:\n').strip()
allowed_name = re.compile(rxin).match
a = 0
for fname in os.listdir(os.getcwd()):
if allowed_name(fname):
a += 1
c = os.path.splitext(fname)
b = (newname + str(a) + c[1])
#os.rename(fname, b)
print((fname, b))
theIndex[124] is a list, so you can just write
theIndex[124].append("m")
You can write
from os.path import join as pjoin
targetfolder = raw_input('enter a target folder:\n').strip()
newname = raw_input('enter a new base name:\n')
newname = pjoin(targetfolder, newname)
...
If you don't want to nuke your jpegs, make a zip file with the whole folder before doing anything.
Sorry for the very slow reply, but for some reason this method is crashing my program... I guess i will have to try to figure out another solution :(
First, if it's crashing your program, there must be an exception traceback.
Also why don't you simply create a normal class and a single instance of the class ?
Google found a patch for scapy.all..sniff, wich allows to stop the sniff function programmatically. You should try this http://trac.secdev.org/scapy/wiki/PatchSelectStopperTimeout
You can write
if colour in ("Green", "Blue", "Red"):
... # do something
else:
... # do something else
Note that in python 3, there are no 'old style class', so that your class is implicitely a subclass of object. Here is a small experiment with python 2.6 and python 3.1
Python 2.6.4 (r264:75706, Oct 27 2009, 15:50:27)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... pass
...
>>> class B(object):
... pass
...
>>> import inspect
>>> inspect.getmro(A) # get the ancestor classes
(<class __main__.A at 0x7f3356d339b0>,)
>>> inspect.getmro(B)
(<class '__main__.B'>, <type 'object'>)
>>> dir(A)
['__doc__', '__module__']
>>> dir(B)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> issubclass(A, object)
False
>>> a = A()
>>> isinstance(a, object) # look at this !
True
>>> issubclass(B, object)
True
Python 3.1.1 (r311:74480, Aug 17 2009, 21:52:39)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... pass
...
>>> class B(object):
... pass
...
>>> import inspect
>>> inspect.getmro(A)
(<class '__main__.A'>, <class 'object'>)
>>> inspect.getmro(B)
(<class '__main__.B'>, <class 'object'>)
>>> dir(A)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> dir(B)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> issubclass(A, object)
True
>>> a = A()
>>> isinstance(a, object)
True
This may work
SP.Popen("c:\\program files\\webteh\\bsplayerpro\\bsplayer.exe d:\\rodin\\rodin.mp4 -stime"+str(d), shell=True)
The str(d) in the argument doesn't work. I suggest that you use the subprocess module
import subprocess as SP
SP.Popen(["c:\\program files\\webteh\\bsplayerpro\\bsplayer.exe", "-stime="+str(d), "d:\\rodin\\rodin.mp4"])
Is this what you mean ?
class Agent:
def __init__(self):
exec "import random" in self.__dict__
ag = Agent()
print ag.random.randrange(100) # this works
print random.randrange(100) # this doesn't work (random not in global namespace)
You could even make a class decorator
def withrandom(cls):
exec "import random" in cls.__dict__
return cls
@withrandom
class Agent:
pass
ag = Agent()
or simpler
class Agent:
import random
You can make a list with your functions
import random
funcs = [func0, func1,func2,func3,func4,func5,func6,func7,func8,func9,]
funcs[random.randrange(10)]() # <- call a random function
random.choice(funcs)() # <- another way
edit: jlm699 was faster :)
By using encapsulation you ensure fidelity of data, and provide a known interface to others who may extend or use your class, making refactoring much less painful.
The author of the article meant that the "property" function replaces getters and setters. In fact python's "property" encapsulates the attribute, and also encapsulates getters and setters !
Hi,
yeah, I played a little around with these functions but I thought that the interpreter starts with Py_Initialize() and ends with Py_Finalize(). That's how it works to this point right? What happens when I call Py_RunString("b=[/* something */]);
Does the function-call ends up in the same function the interpreter (commandline interpreter) would call if I type it in there? And does this happens because I link my programm against the python-lib?
Oh my lord...I'm a little confused. Sorry :S
When you call Py_Initialize, the program creates the module __main__ where your commands are run, and allocates all the memory it needs for the __builtin__ module, etc, exactly as if you were starting a python session with the command "python". The only difference is that there is no interaction with the user, and your program must issue the calls to python functions and extract the data from the imported modules if it needs it. For example, if you want the value of the python variable 'b', you can try
PyObject* main_mod = PyImport_ImportModule("__main__");
PyObject* b = PyObject_GetAttrString(main_mod, "b");
For each function call, you must think about: Can the call return NULL ? Does it return a new reference to the python object ? (it must be decrefed then).
You can add a loop in eyePicker until the user enters a valid colour:
from graphics import *
eye_colours = set("""green brown blue""".strip().split())
def drawCircle(win, centre, radius, colour):
circle = Circle(centre, radius)
circle.setFill(colour)
circle.setWidth(2)
circle.draw(win)
def eyePicker():
while True:
colour = raw_input("Please enter the colour: ").strip()
colour = colour.lower()
if colour in eye_colours:
return colour
else:
print("Invalid colour '{0}'.".format(colour))
print("Possible values are {0}".format(tuple(eye_colours)))
def drawEye():
w = 250
h = 250
win = GraphWin("Eye", w, h)
try:
# center should be at 1/2 width and height
centre = Point(w//2, h//2)
colour = eyePicker()
drawCircle(win, centre, 40, colour)
drawCircle(win, centre, 20, colour)
drawCircle(win, centre, 10, colour)
win.getMouse()
finally:
win.close()
drawEye()
No, the interpreter runs in the main thread. Its role is to execute python code. For example, you can call PyImport_ImportModule, and this will run the python code contained in the given module. There is also the PyRun_*** family (PyRun_File, PyRun_String,...) which execute python code. So your C code can execute python functions or python programs, like you would do in an interpreter shell.
I modified your code to give you a first running version
from graphics import *
def drawCircle(win, centre, radius, colour):
circle = Circle(centre, radius)
circle.setFill(colour)
circle.setWidth(2)
circle.draw(win)
def eyePicker():
colour = raw_input("Please enter the colour: ")
return colour # <- return the picked colour
def drawEye( #win, centre, radius, colour # <- don't need arguments since they are computed in the function's body.
):
w = 250
h = 250
win = GraphWin("Eye", w, h)
# center should be at 1/2 width and height
centre = Point(w//2, h//2)
colour = eyePicker() # <- get the colour
drawCircle(win, centre, 40, colour)
drawCircle(win, centre, 20, colour)
drawCircle(win, centre, 10, colour)
win.getMouse()
win.close()
drawEye()
Hi,
does anybody have a solution to fix this problem. I can't believe that nobody ever wants to printf() a Pyton-String-Object within a C program.
Jonny
Few people write C programs for python 3. I think you should experiment a while with these functions. I interface C++ and python 2.6, but for the main part, I use Py++ which I discovered recently (it works with gcc and boost python). I think you should start serious C programming with python 2.6.
We wouldn't have this problem if Windows machines would ship with Python installed. The real problem is that MS wants to make money with their old VB interpreter.
I think that Van Rossum prefers OSX, and he works for Google, which makes 2 other obstacles.
Do they probably copy short strings sometimes?
I wrote a little test-function that receives a String-Object, uses "PyArg_Parse(args,"s",myString)" and then modifies myString like "myString[1] = 'a'".
The implementation of PyBytes_asString in python 3.1.1 is
char *
PyBytes_AsString(register PyObject *op)
{
if (!PyBytes_Check(op)) {
PyErr_Format(PyExc_TypeError,
"expected bytes, %.200s found", Py_TYPE(op)->tp_name);
return NULL;
}
return ((PyBytesObject *)op)->ob_sval;
}
It means that this function only returns a pointer to the field ob_sval of the PyBytesObject structure: no new memory is allocated. I don't know exactly what happened in your test. Note that the structure is
typedef struct {
PyObject_VAR_HEAD
long ob_shash;
char ob_sval[1];
/* Invariants:
* ob_sval contains space for 'ob_size+1' elements.
* ob_sval[ob_size] == 0.
* ob_shash is the hash of the string or -1 if not computed yet.
*/
} PyBytesObject;
Also note that this code shows you how to check the type of an argument, and how to handle a type error.
I think this (incomplete, 5 years old) [ulr=http://starship.python.net/crew/mwh/toext/toext.html]tutorial[/url] about writing a C extension in python is worth reading.
I think that you should transform your unicode string to a byte array like this
>>> "hello world".encode("ascii")
b'hello world'
and pass the byte array to C. You could then use
char *s = PyByteArray_AsString(pyobj);
instead of the previous PyString_AsString.
The other way is to try to do it from C
temp = PyUnicode_AsASCIIString(pyobj); // must handle NULL return
char *s = PyByteArray_AsString(temp);
...
Py_XDECREF(temp);
If you want to get a C string out of a python object, if the object is a python string you should use
char * s = PyString_AsString(pyobj);
and then use s as a read only C string. If you don't know if the object is a string, you
can use
PyObject* temp = PyObject_Str(pyobj); // convert to python string
char* s = PyString_AsString(temp);
// ... use s read-only
Py_DECREF(temp); // don't use s after this.
About the PyArg_Parse family, the main use of these functions is to convert a tuple of function parameters to C types. They copy small types, like int, double, etc but they don't copy strings, so that the strings read should be used read-only.
This is the code I was trying to use.
while int_rounds > win or int_rounds > loss:
Yes, you should have written 'and' istead of 'or'.
You can try
while rounds > max(player_point, cpu_point)
you forgot the return statement. This is python, not pascal :)
from graphics import *
import math
def distanceBetweenPoints(p1, p2):
x1, y1 = p1.getX(), p1.getY()
x2, y2 = p2.getX(), p2.getY()
return math.sqrt((x2-x1)**2+(y2-y1)**2)
what about nw?.. python gives an error says "the name Point is not defined"
add
from graphics import *
at the top of your file. Also please use code tags to post your python code. And also post python error tracebacks if there is one.
anything around these lines?
def distanceBetweenPoints(p1, p2):
x1, y1 = P1.getX(), P1.getY()
x2, y2 = P2.getX(), P2.getY()
distance = float(math.sqrt((x2-x1)**2+(y2-y1)**2))
The parameters p1 and p2 should not become P1 ad P2 the next line. Also, what does pyhon say ?
For example
def myfunction(pointA, pointB):
xa, ya = pointA.getX(), pointA.getY()
xb, yb = pointB.getX(), pointB.getY()
do_something_with(xa, ya, xb, yb)
You can use the 'key' argument to 'sort' or 'sorted'. Here, Data is a list. You can write
def my_key(item):
return item[1][1] # this returns 3.1 if item is ('1023', ['Name', '3.1', 'SomeData'])
Data.sort(key = my_key)
Data is easily turned into a dictionary:
Data = dict(Data)
L = sorted(Data.items(), key = my_key)
According to your previous post, I think that you are using the "graphics.py" module like this one. In that case, since p1 and p2 are not numbers but Points, you must use first p1.getX() and p1.getY() to get the coordinates of the points.
I ran pylint on this code. Here is the result (note that this depends on my personal configuration of pylint, it may give a different result on your system)
$ pylint --disable-msg W0311 bad.py
************* Module bad
C: 6: Line too long (93/80)
C: 8: Line too long (132/80)
C: 12: Line too long (124/80)
C: 13: Line too long (107/80)
C: 14: Line too long (136/80)
C: 15: Line too long (138/80)
C: 16: Line too long (147/80)
C: 17: Line too long (84/80)
C: 1: Missing docstring
C: 1:findInterestRate: Invalid name "findInterestRate" (should match [a-z_][a-z0-9_]{2,30}$)
C: 1:findInterestRate: Missing docstring
C: 2:findInterestRate: Invalid name "loanAmount" (should match (?:(?:[a-k]|[m-z])|[a-z_][a-z_0-9]{2, 30}))
E: 6:findInterestRate: 2 is not callable
E: 7:findInterestRate: Using variable 'zeroFindings' before assignment
E: 9:findInterestRate: Using variable 'ziggy' before assignment
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.RuntimeError'> ignored
E: 14:findInterestRate: Undefined variable 'finderguess'
Report
======
12 statements analysed.
Duplication
-----------
+-------------------------+------+---------+-----------+
| |now |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines |0 |0 |= |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000 |= |
+-------------------------+------+---------+-----------+
Raw metrics
-----------
+----------+-------+------+---------+-----------+
|type |number |% |previous |difference |
+==========+=======+======+=========+===========+
|code |16 |76.19 |16 |= |
+----------+-------+------+---------+-----------+
|docstring |1 |4.76 |1 |= |
+----------+-------+------+---------+-----------+
|comment |1 |4.76 |1 |= |
+----------+-------+------+---------+-----------+
|empty |3 |14.29 |3 |= |
+----------+-------+------+---------+-----------+
Statistics by type
------------------
+---------+-------+-----------+-----------+------------+---------+
|type |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
|module |1 |1 |= |0.00 |0.00 |
+---------+-------+-----------+-----------+------------+---------+
|class |0 |0 |= |0.00 |0.00 …