*args and **kwargs
Ok, this is probably definitely a newbie question, but I have looked all over the Python library reference material and tutorials which I can find online and I cannot find a clear definition of what these are and more importantly how to use them. From what I can tell from their use in the examples I've seen, they are for passing a variable number of arguments to a function (which I need to do in a program I am working on). But how do you use them? Is there a fixed order in which the arguments within *arg or **kwarg should be passed or will be called within a function? I realize this probably involves a long- winded answer to a very simple and common programming problem, so if someone has a link to TFM, I'll gladly go RTFM. I just can't find it. -- http://mail.python.org/mailman/listinfo/python-list
Re: *args and **kwargs
> I hope this example code will help you understand: >>Code Snipped<< OOH!! That makes perfect sense, thanks!, *args are passed as a turple, **kwargs are passed as a dictionary. That means **kwargs is probably what I want. JonathanB -- http://mail.python.org/mailman/listinfo/python-list
Conceptualizing Threading
I have a multi-access problem that I'm pretty sure needs to be solved with threading, but I'm not sure how to do it. This will be my first foray into threading, so I'm a little confused by all of the new landscape. So, I'm going to lay out the problem I'm facing and if someone could point me towards a good example of what I need to do, that would be great. I read THE tutorial, and while it made since to me in an esoteric sense, I'm not sure how to implement it. I have a program which will be logging who took what orders. These orders need to have sequential order numbers. SR001001, SR001002, SR001003, etc. Problem is I'm not sure how many people will be accessing this program at the same time. I thought about separating the order number into its own file and the having a function open it, read it, increment it, write it, and close it really quick to limit the chance of two people pulling the same number. Then I heard found threading. So this sounds like a consumer/producer problem, right? So I think I need to use a Queue to crank out quote numbers and have the users connect to the queue to get their number. Does that mean I'm looking at two separate programs, a server and a client? Where do I separate the programs? I was just about to give up and have quote number assignment be manual (with error checking), but I thought I should check here first and see if someone could help me wrap my brain around this problem. You'll never learn if you never try, right? -- http://mail.python.org/mailman/listinfo/python-list
Re: Conceptualizing Threading
> You described how threads introduce a problem in your program -- that of > generating a sequence of sequential identifiers -- but you didn't describe > the problem that threads are solving in your program. Maybe you don't > need them at all? What led you to threading in the first place? > > Jean-Paul Well, the problem I thought they would solve is ensuring everyone got a sequential number. But I suppose they wouldn't solve that, since from what I gather thread access is somewhat arbitrary. So then, here is the crux of the issue. Worst case scenario, this program could be accessed by 5-10 people at a time and I need each one to have the current information. There are two places I know of that there might be multi-access problems. 1) This program is so that we can track one team passing assignments to another. Right now I have the names of everyone in team 2 in a list. People from team one launch this program and the program grabs a pointer (stored in a separate file). If person A launches the program and person B launches the program before person A assigns an order, they will both have the same pointer, so both orders will go to the same person. 2) Each assignment has a distinct identifier, which increments by 1 for each assignment (SR001001, SR001002, etc). Either these can be assigned manually (the current method), or they can be assigned automatically. If they are assigned manually, I need a way to show them the most recent number (that would be easy), if they are assigned automatically I need a way to save the number and pass the incremented number along (just like the pointer). But I have the same problem here as above. If two people launch the program at roughly the same time, they will pull the same data. Since these assignments tend to come in spurts, concurrent access is likely to be a problem. So, given those parameters (the rest of this program is a breeze, there's a class for each person on Team 2 and the class holds some info about them and a dictionary of assignments with the assignment number for the key and a value of [assigner, numberAssigned], the only other tricky thing for me has been logging because I've never had to do much of it before), how can I prevent these problems? The only thing that jumps out at me is a server/client model where a server runs and compiles all the entries, spitting back the result to each individual client. That way, all the working code lives in the server, ensuring that the working thread always has the right information, while the clients only pass data between the user and the server. But I guess that isn't technically multi-threading is it. -- http://mail.python.org/mailman/listinfo/python-list
Discover instance variables
Ok, I know there has to be a way to do this, but my google-fu fails me (once more). I have a class with instance variables (or should they be called attributes, I'm newish to programming and get really confused with OO sometimes), like the one in this example: class Foo(): self.a = "bar" self.z = "test" self.var = 2 foo = Foo() I want to print a list of the variables (strings, integers, etc) in Foo, without knowing their names. So that the user who needs to change a peice of information can view the variable list, enter the name of the variable they need to change and then make the change. This is what I'd like a sample run to look like: Attributes for foo: a = bar z = test var = 2 Change: a New value: foobar Change made! I can handle the formatting and changing the variable itself, no problem, but how do I get a list of all the variables in a class instance? I almost put a list in there called vars and appended all the variables to it so I could iterate the list, but this sounds like something useful enough that someone has come up with a better way to do it than that. It almost looks like self.__dir__() is what I want, but that returns methods as well, correct? I only want variables, but I can't think of how to do a list comprehension that would remove the methods. JonathanB -- http://mail.python.org/mailman/listinfo/python-list
Re: Discover instance variables
> > class Foo():
> > self.a = "bar"
> > self.z = "test"
> > self.var = 2
>
> That's unlikely to work, though: the code is in the context of the
> class, not one of its methods, so unless you happen to be declaring a
> class inside another class's method it's unlikely that there's going to
> be a "self" around when those three lines execute.
Ah, I see. Trouble is I write most of my code on a computer that
doesn't have python (shared computer and I don't have permissions to
install). So I code it here, email it to myself, and test it at home.
I had my debugged code at home so I couldn't post a working example.
Here's working example.
class World():
def __init__(self, name, WTN, Ag, Na, Ex, In, Ni, Al, Port, Type,
Dia, Grav, Atmosphere, Hyd, Climate, Pop, Gov, CR, TL, Wealth,
Trade=None, notes=None):
self.name = name
self.WTN = WTN
self.Ag = Ag
self.Na = Na
self.Ex = Ex
self.In = In
self.Ni = Ni
self.Al = Al
self.Port = Port
self.Trade = Trade
self.Type = Type
self.Dia = Dia
self.Grav = Grav
self.Atmosphere = Atmosphere
self.Hyd = Hyd
self.Climate = Climate
self.Pop = Pop
self.Gov = Gov
self.CR = CR
self.TL = TL
self.Wealth = Wealth
self.notes = notes
The code to execute this is:
def world_info():
# code to prompt for each variable
world = World(name, WTN, Ag, Na, Ex, In, Ni, Al, Port, Type, Dia,
Grav, Atmosphere, Hyd, Climate, Pop, Gov, CR, TL, Wealth)
So given that example, is there a clean way to get this output:
Data for Earth:
Name = Earth
WTN = 5.0
Ag = 0
Na = 0
...
...
Notes = None
> [name for name in dir(x) if not callable(name) and not
> name.startswith("__")]
That does looks almost exactly like what I want I think (I'm still
learning to read code to learn what it does, but from what it looks
like this does a list comprehension that removes everything callable
and that starts with "__")
> [name for name in dir(x) if not callable(name) and not
> name.startswith("__")]
>
> might come close - I presume you don't want __doc__ and the like.
>
--
http://mail.python.org/mailman/listinfo/python-list
Read and Write the same file
Ok, so this is the scenario. I need to create a simple, no-frills XML editor for non-technical users. It doesn't have to do anything fancy, what I want is a series of text boxes with the text contents of the elements pre-printed. Then the users can type their changes into the text boxes and click submit and it will load the changes in. So here is the problem, this means I need to open the same file as both read and write. How do I do this? I'm slowly learning the DOM stuff that I need to know to do this, but this file thing I haven't been able to find anywhere. JonathanB -- http://mail.python.org/mailman/listinfo/python-list
Re: Read and Write the same file
> Well the most straight forward approach is to read data from the file > into memory. Let the user make any changes. Then save the data back to > the file, overwriting the oringinal copy. Now, this only really works > if you're dealing with small files. > > Regardless though, you never really need to have a file open for both > reading and writing. Since they occur (so it sounds) at distinct times > during your program flow, just open it twice: the first to read, the > second to write. > > Ian That makes sense. The largest document is >10K, so it shouldn't be a problem. -- http://mail.python.org/mailman/listinfo/python-list
Windows command line not displaying print commands
Ok, I'm sure this is really simple, but I cannot for the life of me get any print statements from any of my python scripts to actually print when I call them from the windows command line. What am I doing wrong? hello.py: print "Hello World!" command line: E:\Python\dev>python hello.py E:\Python\dev> I'm using Python 2.6.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows command line not displaying print commands
On Mar 30, 6:28 pm, John Machin wrote: > On Mar 31, 8:37 am, Irmen de Jong wrote: > > Does just typing: > > > python Yes, just typing python takes me to my interactive prompt > > Or do you have a module in your E:\Python\dev directory called 'os', 'sys' > > or something > > else that may clobber one of the default library modules. The only module in the directory is called pyfind.py > > or perhaps there's a file named python.bat that does nothing. > > What directory is Python installed in? What does your Windows PATH > look like? Is this your very first attempt to do anything at all with > Python or have you managed to get any output from a Python script > before? If the latter, what have you changed in your environment? Does > E: refer to a removable disk? Unfortunately, this problem is on my work computer, so I'm not in front of it right now. I've done the development on this in PortablePython, but I have python installed in C:/Python25 and that should be in my path (I went though and added it). I've never run a script that output to the command line before, only django apps. Django will output stuff though, which makes me wonder if I've somehow borked my stdout in the script. Not sure how I could have done that, but I'll post the script I've written in the next post just in case I'm somehow messing up the calls (although "print var" seems fairly user-proof...). E: does refer to a removable disc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows command line not displaying print commands
#This is pyFind, a python replacement for find(1)
import os, sys, re, fnmatch
from os.path import join
from optparse import OptionParser
usage = "usage: %prog --name [directory1 directory2]"
parser = OptionParser(usage=usage)
parser.add_option("--regex", dest="regex",
help="REGEX MATCHING DOES NOT WORK AT THIS TIME, ONLY USE THE --name
OPTION!!!")
parser.add_option("--name", dest="name",
help="Unix style pattern matching search for a file by filename.")
def set_directories(args, directories):
"""initialize directory list to ensure that all subsequent loops
will
loop correctly. directories is a created list and args is the
positional
arguments from OptionParser."""
if args != []:
for arg in args:
#We have to use os.splitdrive() to support Windows. Otherwise you
cannot search
#different drive letters.
(drive, tail) = os.path.splitdrive(arg)
directories.append([drive, tail])
#For handling the default case, which is to search in current working
directory
else: directories.append(os.path.splitdrive(os.getcwd()))
def regex_matcher(value, names):
if value == None:
return names
else:
regex = re.compile(value)
return [name for name in names if regex.search(name)]
def glob_matcher(value, names):
if value == None:
return names
else: return [name for name in names if fnmatch.fnmatch(name,
value)]
if __name__ == "__main__":
(options, args) = parser.parse_args()
directories = []
set_directories(args, directories)
for directory in directories:
#If we are in windows, directory[0] will be True. In that case we must
switch
#to the root of that drive letter before we can traverse to the
requested
#directory.
if directory[0] == True:
os.chdir(directory[0])
#Now that we know we are either in the right drive letter or in a Unix
#environment, we can change to the proper directory.
os.chdir(directory[1])
for root, dirs, files in os.walk(os.getcwd()):
#results = regex_matcher(options.regex, files)
#regex = re.compile(options.regex)
#results = [name for name in files if regex.search(name)]
results = glob_matcher(options.name, files)
if results != []: print"/n".join(results)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Windows command line not displaying print commands
I think I found the problem. I recently removed Python 2.5 and replaced it with 2.6. When I got in, I tried to run some django commands and even they weren't producing output. On a hunch, I tried to uninstall 2.6 and reinstall it, since now even django wasn't producing output. When I tried, it told me that I couldn't because it wasn't installed. I had to delete the folder and manually go through and delete every instance of "python" in my registry. However, when I reinstalled 2.6, it worked. Some of the registry entries were still pointing to the defunct Python25 path rather than Python26. Now both the simple hello.py script and the bigger script that I really wanted to get working are producing output. I apologize for the confusion caused by going the wrong direction with my troubleshooting (from the simplest possible script to the more complex script), next time I will be more sensible in my troubleshooting. -- http://mail.python.org/mailman/listinfo/python-list
extra rows in a CSV module output when viewed in excel 2007
The subject basically says it all, here's the code that's producing the csv file: def write2CSV(self,output): writer = csv.writer(open(output, 'w'), dialect='excel') writer.writerow(['Name','Description','Due Date','Subject', 'Grade','Maximum Grade', self.name, self.grade]) for row in self.assignment_list: writer.writerow(row.output2list()) return True Here's the text from the csv file my test-run outputs: Name,Description,Due Date,Subject,Grade,Maximum Grade,Test Student,2 Math Homework 8/21,Math Review pp. 103-104,2010-08-13,Math,10,10,, Math Test,Chapter 5,2010-09-21,Math,45,50,, Science Test,Matter,2010-09-11,Science,400,500,, When I view it in Excel, there's an extra row between every result. How can I remove those? -- http://mail.python.org/mailman/listinfo/python-list
Re: extra rows in a CSV module output when viewed in excel 2007
On Aug 13, 3:52 pm, alex23 wrote: > On Aug 13, 4:22 pm, JonathanB wrote: > > > writer = csv.writer(open(output, 'w'), dialect='excel') > > I think - not able to test atm - that if you open the file in 'wb' > mode instead it should be fine. changed that to writer = csv.writer(open(output,'wb'),dialect='excel') Now I get this error: TypeError: must be bytes or buffer, not str I'm using Python 3.1, maybe that changes things? -- http://mail.python.org/mailman/listinfo/python-list
Re: extra rows in a CSV module output when viewed in excel 2007
On Aug 20, 9:10 am, MRAB wrote: > JonathanB wrote: > > On Aug 13, 3:52 pm, alex23 wrote: > >> On Aug 13, 4:22 pm, JonathanB wrote: > > >>> writer = csv.writer(open(output, 'w'), dialect='excel') > >> I think - not able to test atm - that if you open the file in 'wb' > >> mode instead it should be fine. > > > changed that to > > writer = csv.writer(open(output,'wb'),dialect='excel') > > > Now I get this error: > > > TypeError: must be bytes or buffer, not str > > > I'm using Python 3.1, maybe that changes things? > > You want to open the file in text mode, but not write Windows line > endings (CRLF) for each newline: > > writer = csv.writer(open(output, 'w', newline=''), dialect='excel') That was it! Thank you, I knew it was something stupid. It's been so long (6 months) since I coded, I forgot about how Windows/Mac mangle line endings. -- http://mail.python.org/mailman/listinfo/python-list
Entry Level Python Jobs
I am a self-taught Python programmer with a liberal arts degree (Cross- cultural studies). I have been programming for several years now and would like to get a job as a python programmer. Unfortunately most of the job posts I have seen are for CS Majors or people with experience. Is there a place I can look for job posts for entry level positions requiring no experience? For the hiring managers, if the job post said "CS Major" in the requirements, would you consider a liberal arts major at all? -- http://mail.python.org/mailman/listinfo/python-list
Re: Entry Level Python Jobs
Ok, so what I'm hearing is "Get a code portfolio together and watch the job board on python.org." Thanks for the advice! I've been watching the python job board 3-4 times a week and I've been working my way through the Project Euler problems in my free time. I also have a trade generator that I wrote up to support a Traveller game I was running a while back, but that code is old (the first non- trivial program I ever wrote) and really fairly buggy. The user interface is basically an infinite recursion that I sys.exit() out of when I'm through, which means the code slows considerably as you do more stuff in it because each trip back to the main menu is a recursive call to the main() function. Hey, I was young and naive. I'm working on cleaning it up right now. Any other tips? -- http://mail.python.org/mailman/listinfo/python-list
