Re: Urllib vs. FireFox
Right. If you want to get the same results with your Python script that you did with Firefox, you can modify the browser headers in your code. Here's an example with urllib2: http://vsbabu.org/mt/archives/2003/05/27/urllib2_setting_http_headers.html By the way, if you're doing non-trivial web scraping, the mechanize module might make your work much easier. You can install it with easy_install. http://wwwsearch.sourceforge.net/mechanize/ -- http://mail.python.org/mailman/listinfo/python-list
Re: from package import * without overwriting similarly named functions?
If you're concerned about specific individual functions, you can use: from package1 import some_function as f1 form package2 import some_function as f2 -- http://mail.python.org/mailman/listinfo/python-list
Confused: looking for a simple XML parser
Hello, I am a Python programmer facing my first small XML project. I am looking to find a simple tool to take an XSD file and convert the XSD tree structure to another text format (e.g. an adjacency matrix for the tree's graph), or convert one xml file format definition into another, non-xml one. I don't need to validate XML documents created by this schema or do anything else fancy. I just need to be able to traverse this tree programmatically and find which child attributes belong to which parent attributes, etc. There seem to be so many Python libraries and programs out there that I don't know what to use. What tool should I use? Thanks, Rex -- http://mail.python.org/mailman/listinfo/python-list
Submitting forms over HTTPS with mechanize
Hello,
I am working on an academic research project where I need to log in to
a website (www.lexis.com) over HTTPS and execute a bunch of queries to
gather a data set. I just discovered the mechanize module, which seems
great because it's a high-level tool. However, I can't find any decent
documentation for mechanize apart from the docstrings, which are
pretty thin. So I just followed some other examples I found online, to
produce the following:
baseurl = 'http://www.lexis.com/'
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-Agent', 'Firefox')]
br.open(baseurl)
br.select_form(name="formauth")
br["USER_ID"]="my_user_id"
br["PASSWORD"]="my_password"
result = br.submit()
This code hangs at br.submit(), and I can't tell what I'm doing wrong.
Typically I would inspect the HTTP data with an HTTP debugging proxy
(Fiddler), but I guess since this is HTTPS I can't do that. Any
glaring errors in my code?
By the way, does anyone have suggestions for Python modules that I
should use instead of mechanize (and that are sufficiently easy)? If
mechanize fails, I might try modifying some similar Perl code a friend
sent me that logs into lexis.com.
Thanks so much,
Rex
--
http://mail.python.org/mailman/listinfo/python-list
Re: Submitting forms over HTTPS with mechanize
On Sep 3, 10:17 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> Rex wrote:
> > Hello,
>
> > I am working on an academic research project where I need to log in to
> > a website (www.lexis.com) over HTTPS and execute a bunch of queries to
> > gather a data set. I just discovered the mechanize module, which seems
> > great because it's a high-level tool. However, I can't find any decent
> > documentation for mechanize apart from the docstrings, which are
> > pretty thin. So I just followed some other examples I found online, to
> > produce the following:
>
> > baseurl = 'http://www.lexis.com/'
> > br = mechanize.Browser()
> > br.set_handle_robots(False)
> > br.addheaders = [('User-Agent', 'Firefox')]
> > br.open(baseurl)
> > br.select_form(name="formauth")
> > br["USER_ID"]="my_user_id"
> > br["PASSWORD"]="my_password"
> > result = br.submit()
>
> > This code hangs at br.submit(), and I can't tell what I'm doing wrong.
> > Typically I would inspect the HTTP data with an HTTP debugging proxy
> > (Fiddler), but I guess since this is HTTPS I can't do that. Any
> > glaring errors in my code?
>
> > By the way, does anyone have suggestions for Python modules that I
> > should use instead of mechanize (and that are sufficiently easy)? If
> > mechanize fails, I might try modifying some similar Perl code a friend
> > sent me that logs into lexis.com.
>
> > Thanks so much,
>
> > Rex
>
> I've used mechanize quite successfully but others have suggested
> Twillhttp://twill.idyll.org/. It seems to be at least documented.
>
> -Larry
Thanks for the reply, Larry. I ran my code again and it worked; there
was probably some temporary issue with either my computer or the
server that caused it to hang.
--
http://mail.python.org/mailman/listinfo/python-list
Is it possible to download only the of a web page?
I am writing a script that executes a bunch of queries through a form on a website and reads the results. I am only interested in the section in the of each web page. Currently, each page the server returns is about 100kb and contains a bunch of HTML and Javascript, all of which I don't need; I don't want to waste bandwidth or consume too much of the server's resources. I just need the string. Is there any way to download less than the entire web page? -- http://mail.python.org/mailman/listinfo/python-list
Running Python interpreter in Emacs
Hi,
I'm interested in running a Python interpreter in Emacs. I have Python
extensions for Emacs, and my python menu lists "C-c !" as the command
to run the interpreter. Yet when I run it I get the message "Spawning
Child Process: invalid argument." What do I need to do/download to fix
this?
I read in a post in this group from a while back where someone had the
following lines in his .emacs file:
(setq interpreter-mode-alist
(cons '("python" . python-mode)
interpreter-mode-alist))
Does that have something to do with it? Do I have to set my load-path
to my python interpreter?
Thanks,
Rex
--
http://mail.python.org/mailman/listinfo/python-list
Re: Running Python interpreter in Emacs
Hi Skip and Philippe. I added the path for Python to PATH, but I still get the same message (when I try executing the current buffer, I get the message: "The system cannot find the path specified." Philippe, I have the above lines of code in my .emacs file. As for my environment, I'm running Emacs 21.4 on Windows XP. Thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: Running Python interpreter in Emacs
I have the following in my .emacs: (add-to-list 'load-path "C:\Program Files\Python24") Is that enough? I didn't see anything similar to that in your .emacs file, so I'm wondering if I'm supposed to add the path to my PATH elsewhere. Thanks, Rex -- http://mail.python.org/mailman/listinfo/python-list
Re: Running Python interpreter in Emacs
I went to My Computer | Properties | Advanced | Environment Variables and added c:\program files\python24 to both the PYTHONPATH and Path variables. Still no luck. I don't know whether the path I'm talking about is the same as the $PATH you referred to, or whether I'm supposed to put python.exe explicitly somewhere; could someone refer me to a place where I can read about these things? Thanks! Rex -- http://mail.python.org/mailman/listinfo/python-list
Debugger Confusion
I'm a little confused about which debugging utilities do what, and which I should use for my Python code. I'd like to be able to step through my code, insert breakpoints, etc. I haven't been able to do this yet (I'm using Emacs on Windows). I have seen references to GDB, GUD, PDB, and others. Which ones do I need? Thanks, Rex Eastbourne -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugger Confusion
Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugger Confusion
One thing: is it possible to go through the code within emacs? Doing it on the command line is useful, but it would be very helpful if I could have a little marker within the emacs buffer that showed me where I am. Rex -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugger Confusion
Also, when I try running pdb in my Emacs shell, I get very weird behavior: for instance, I'll hit 'h' and enter twenty times with no output. Then, all of a sudden, twenty output messages will pop up. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running Python interpreter in Emacs
Yes! Thank you so much! (For some reason, by the way, I had to copy python.exe to my c:/ directory, since the computer could never find the path in program files/python24. But when I did that, and used setq-py-python-command, it worked. I now have python.exe in two locations.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Running Python interpreter in Emacs
Yes, I knew that copying it to my root was a kludge. But between that and not having it work, I chose the former. (As you might be able to tell from my posts, I tried multiple things and was frustrated.) I tried putting quotes around "c:\program files\python24". It still didn't work. I chose to install Python in Program Files. I didn't know it would cause any problems; I just thought it was good to have all my programs in the same place. I guess I was wrong. -- http://mail.python.org/mailman/listinfo/python-list
Printing literal text of an argument
Hi all,
I've written the following simple macro called debug(aname, avalue)
that prints out the name of an expression and its value:
def debug(aname, avalue):
print aname, 'is':
pprint.pprint(avalue)
An example call is:
debug('compose(f1,f2)', compose(f1,f2))
Writing the exact same thing twice (one in quotes and the other not)
sets off an alarm in my head. Is there a way to make this function take
only one argument, and use both its value and its literal form? On a
slightly different topic, is it also possible to make the macro print
the line number where the function was first called?
Thanks,
Rex
--
http://mail.python.org/mailman/listinfo/python-list
Re: Printing literal text of an argument
Thanks. I adapted it a bit:
def debug(foo):
print foo, 'is:'
exec('pprint.pprint(' + foo + ')')
But I'm getting "NameError: name 'foo' is not defined," since foo is
not defined in this scope. (The function works beautifully when I'm
dealing with global variables, which is very rarely).
Any way around this?
Rex
--
http://mail.python.org/mailman/listinfo/python-list
Bicycle Repair Man usability
Are there any Bicycle Repair Man users here? I recently got PyDev for Eclipse, which comes with BRM. I am disappointed with what I've seen, although I'm not sure if I'm using its full functionality. According to PyDev's documentation, this is what one can do: -Rename a function/variable -Block of code --> method and a method call -Get rid of extra variables by shifting them inline (e.g.: a=1;b=2;c=a+b --> c=1+2) I'm not aware of anything else that can be done, as BRM's documentation is extremely thin. Is anyone else aware of other uses? It's a shame this project is not active; it seems like such a great idea. Rex -- http://mail.python.org/mailman/listinfo/python-list
Bicycle Repair Man usability
Are there any Bicycle Repair Man users here? I recently got PyDev for Eclipse, which comes with BRM. I am disappointed with what I've seen, although I'm not sure if I'm using its full functionality. According to PyDev's documentation, this is what one can do: -Rename a function/variable -Block of code --> method and a method call -Get rid of extra variables by shifting them inline (e.g.: a=1;b=2;c=a+b --> c=1+2) I'm not aware of anything else that can be done, as BRM's documentation is extremely thin. Is anyone else aware of other uses? It's a shame this project is not active; it seems like such a great idea. Rex -- http://mail.python.org/mailman/listinfo/python-list
Statistics...help with numpy/scipy install
I'm new to Python with a new windows 8 machine (64-bit OS). Learning programming mainly for fun. Naturally I downloaded Python 3.3 (who doesn't want the latest and greatest). What I want involves functions related to the normal distribution. Based on my google research, it appears that SCIPY is a good way to go. That requires NUMPY. I don't seem to find an install that works for my environment which leads to the questions on this post: Is there an install for my environment and if so, where do I get it? If not, is there another package I should use? Or do I need to bite the bullet and install an earlier version of Python. Suggestions and comments appreciated. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
The setup of numpy-1.7.0 leads to a Setup window with a message: "Python 3.3 is required for this package. Select installation to use:". Below that is an empty list box. Below that is an edit box for the Python Directory. I have Python 3.3 installed on c:\Python33. On Sunday, February 10, 2013 1:10:32 PM UTC-5, Mark Lawrence wrote: > On 10/02/2013 17:35, Rex Macey wrote: > > > I'm new to Python with a new windows 8 machine (64-bit OS). Learning > > programming mainly for fun. Naturally I downloaded Python 3.3 (who doesn't > > want the latest and greatest). What I want involves functions related to > > the normal distribution. Based on my google research, it appears that SCIPY > > is a good way to go. That requires NUMPY. I don't seem to find an install > > that works for my environment which leads to the questions on this post: Is > > there an install for my environment and if so, where do I get it? If not, > > is there another package I should use? Or do I need to bite the bullet and > > install an earlier version of Python. Suggestions and comments > > appreciated. Thanks. > > > > > > > So what exactly went wrong when you tried to install this > > http://sourceforge.net/projects/numpy/files/NumPy/1.7.0/ using commands > > that you haven't given us and got error messages that you also haven't > > given us? > > > > -- > > Cheers. > > > > Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
I should have added that the setup gives an error window "Cannot install" "Python version 3.3 required, which was not found in the registry." On Sunday, February 10, 2013 5:11:20 PM UTC-5, Rex Macey wrote: > The setup of numpy-1.7.0 leads to a Setup window with a message: "Python 3.3 > is required for this package. Select installation to use:". Below that is an > empty list box. Below that is an edit box for the Python Directory. > > > > I have Python 3.3 installed on c:\Python33. > > > > On Sunday, February 10, 2013 1:10:32 PM UTC-5, Mark Lawrence wrote: > > > On 10/02/2013 17:35, Rex Macey wrote: > > > > > > > I'm new to Python with a new windows 8 machine (64-bit OS). Learning > > > programming mainly for fun. Naturally I downloaded Python 3.3 (who > > > doesn't want the latest and greatest). What I want involves functions > > > related to the normal distribution. Based on my google research, it > > > appears that SCIPY is a good way to go. That requires NUMPY. I don't > > > seem to find an install that works for my environment which leads to the > > > questions on this post: Is there an install for my environment and if so, > > > where do I get it? If not, is there another package I should use? Or do I > > > need to bite the bullet and install an earlier version of Python. > > > Suggestions and comments appreciated. Thanks. > > > > > > > > > > > > > > > > > > > So what exactly went wrong when you tried to install this > > > > > > http://sourceforge.net/projects/numpy/files/NumPy/1.7.0/ using commands > > > > > > that you haven't given us and got error messages that you also haven't > > > > > > given us? > > > > > > > > > > > > -- > > > > > > Cheers. > > > > > > > > > > > > Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
I am sure I have python installed. I have been running it. in command line the window title is c:\python33\python.exe. The first line begins Python 3.3.0. Later in the line is the string "64 bit ] on Win32". Thus it appears I am trying to run a 32bit numpy with a 64bit python. (Seems like a big ole 64 bit python should be able to swallow a little 32 bitty numpy). Is there a 64bit numpy? If not why not? Can someone get on this? Seriously, I'm under the impression that I need the 64 bit python because I have a 64 bit OS. -- http://mail.python.org/mailman/listinfo/python-list
Is there a graphical GUI builder?
I'm new to Python and only a hobbyist programmer. A long time ago I used Microsoft's Visual Basic which had a nice (graphical) facility for creating GUIs which was part of the development environment. I'm wondering if there's a utility for Python to build GUIs. I see that there is TKinter, which is a scripting function to build GUIs. To be clear, I'm looking for a graphical interface to build GUIs. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
tkinter / gui
Here is one general and one specific question about creating GUIs using tkinter from a newbie. I have created a class in which to hold some data. I want to create a GUI to get the data from the user and store it in the object. Browsing the web I see that a lot of examples on GUIs have the forms put into classes. I'm not clear why. Why is that? Second, I've created a form with a bunch of widgets on it, one of which is a listbox. This is done with a script, not a class. I've defined a method that responds to a Button Release event. I know this works because I can print the value selected in the listbox while within the method. However, I want the value of the listbox after I've closed the form. How do I get that? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
listbox binding..what is the current selection?
I have a listbox with two strings "Fixed" and "Random". It is bound by the
following statement:
lbLengthtype.bind('',set_lengthtype)
Here's the beginning of the set_lengthtype code:
def set_lengthtype(event=None):
s=lbLengthtype.get(tk.ACTIVE)
print(s)
.
The print(s) statement is for debugging. If 'Random' was selected and the user
clicks 'Fixed', then Random will print. I would like to know what the user
just selected, not what was selected before the user clicked. How can I
determine the current selection? Thanks.
--
http://mail.python.org/mailman/listinfo/python-list
Re: listbox binding..what is the current selection?
Thanks. I have spent time with the docs, at least with the Python v3.3 and tkinter v8.5 (pdf). I wish they had more examples. My approach is to browse the docs, try a program, fail, read the docs, try again. When I can't figure it out, I post. I appreciate the help. On Tuesday, March 5, 2013 8:26:12 PM UTC-5, Rick Johnson wrote: > On Tuesday, March 5, 2013 6:54:45 PM UTC-6, Rex Macey wrote: > > > I have a listbox with two strings "Fixed" and "Random". > > > [...] Here's the beginning of the set_lengthtype code: > > > > > > def set_lengthtype(event=None): > > >s=lbLengthtype.get(tk.ACTIVE) > > >print(s) > > >. > > > > > > The print(s) statement is for debugging. If 'Random' was > > > selected and the user clicks 'Fixed', then Random will > > > print. I would like to know what the user just selected, > > > not what was selected before the user clicked. How can I > > > determine the current selection? Thanks. > > > > Use "listbox.nearest(event.y)" instead of "get(ACTIVE"). And maybe you should > spend some time reading the docs eh? > > > > http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: list.append not working?
Wildemar Wildenburger wrote:
> Abhishek Jain wrote:
>> with every iteration your previous values are overwritten ('md' is a
>> dictionary) so thats why your are observing this ouput..
>>
>> check if the following patch solves your problem
>>
>> for entity in temp:
>> md['module']= entity.addr.get('module')
>> md['id']=entity.addr.get('id')
>> md['type']=entity.addr.get('type')
>> #print md
>> mbusentities.append(md)
>> md = {}
>> #print mbusentities
>>
>>
>> Regards
>> Abhi
> This will work, but may I suggest putting the md = {} line at the
> *beginning* of the loop?
> I find seeing it at the end HIGHLY confusing. Declaring it in the
> beginning makes sense, because you declare/initialize, then use it. But
> using and *then* initializing it for the next iteration is kind of
> quirky, because it breaks the logical encapsulation I would like to see
> in *one* loop iteration.
>
> /W
Hear, hear! to the declaration at the beginning. Just went through a
long bug search due to a similar behaviour. Terrible. I try to view
the body of a loop as if it were a separate function/method. If it
makes sense from that point of view, it will make sense in 3 months. I
mean, why would you want ot initialize something when you're done with it?
Cheers,
Rex
--
http://mail.python.org/mailman/listinfo/python-list
Re: Calling Exe from Python
muhamad.abbas : > Hello Folks, > > This is what i am required to do. > Call an executable from my python script, and when the executable is > finished running, i should continue with my python script. > > I have tried "os.exec()" but it calls the executable and never returns > to the calling python script. > I tried "os.fork" it will start an independent process, > since logic of my program depends on the results of executable. > > I am unable to figure, how to do it. > Hope you folks would help me. > > ~JinBaba > I use import os os.spawnl(os.P_WAIT, pathToExe, pathToExe, parm1, parm2, parm3, ) Remember that pathToExe must also be the first parameter. There are many other flavors of os.spawn, check documentation! Good luck, Rex -- http://mail.python.org/mailman/listinfo/python-list
Re: 0 == False but [] != False?
Steven D'Aprano :
> On Thu, 24 May 2007 06:59:32 +, Tim Roberts wrote:
>
>> As a general rule, I've found code like "if x == False" to be a bad idea in
>> ANY language.
>
>
> Surely that should be written as "if (x == False) == True"?
>
>
Why compare to False?
" if not x : ... "
It really doesn't matter if x is False or if it evaluates to False. Many
things evaluate to False like [], (), 0, "", None and a few other things.
>>> def tf(thing):
... if thing : print "True thing", thing
... elif not thing : print "False thing",thing
... else : print "No thing"
...
>>> tf([])
False thing []
>>> tf([1])
True thing [1]
>>> a = ()
>>> tf(a)
False thing ()
>>> a=(0)
>>> tf(a)
False thing 0
>>> a= (1,2,3)
>>> tf(a)
True thing (1, 2, 3)
>>> tf("abc")
True thing abc
>>> tf("")
False thing
>>>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Handwriting Recognition
[EMAIL PROTECTED] schrieb/wrote: >>> import handwriting >>> ... >>> http://docs.python.org/lib/module-handwriting.html >>> ha ha, I kid, I kid. >>> I don't think this is an easy problem to solve. You'd probably want >>> Python to be a wrapper around whatever hand-writing recognition >>> software you find or buy. I know handwriting recognition software can >>> read the hand-writing on checks, so that may be a starting point. > > I once had someone explain to me how this actually works from a purely > mathematical standpoint and the topic was fascinating. Unfortunately > most of the math went straight over my head and, in the end, it was > explained to me that math itself is the problem. Handwriting (and > almost any other uncontrolled input) is usually emotional, not logical > in the strictest sense (which is why handwriting experts can tell a > great deal about a person from the handwriting). If you can mimic > handwriting (or any emotional) input in a mathematical expression then > you wouldn't be far from playing "god". > > This was the only thing I could find that may be helpful to you: > > http://sourceforge.net/projects/tomoe/ > > This includes a "stroke editor" and an engine which may suit your > needs. Hope this helps.. > > Good luck! > We use a neural net. Can't say much as I didn't write it. It takes a lot of training though (by training I mean training the software with each symbol). Cheers, Rex -- http://mail.python.org/mailman/listinfo/python-list
read lines
Hi, I have a text file like this;
1 -33.453579
2 -148.487125
3 -195.067172
4 -115.958374
5 -100.597841
6 -121.566441
7 -121.025381
8 -132.103507
9 -108.939327
10 -97.046703
11 -52.866534
12 -48.432623
13 -112.790419
14 -98.516975
15 -98.724436
So I want to write a program in python that reads each line and
detects which numbers of the second column are the maximum and the
minimum.
I tried with;
import os, sys,re,string
# first parameter is the name of the data file
name1 = sys.argv[1]
infile1 = open(name1,"r")
# 1. get minimum and maximum
minimum=0
maximum=0
print " minimum = ",minimum
print " maximum = ",maximum
while 1:
line = infile1.readline()
ll = re.split("\s+",string.strip(line))
print ll[0],ll[1]
a=ll[0]
b=ll[1]
print a,b
if(b
print ll[0],ll[1]
IndexError: list index out of range
Could anybody help me ?
Thanks
--
http://mail.python.org/mailman/listinfo/python-list
multidimensional "arrays"
in python, when I want to use arrays, I follow this way; DATA = [0] * nint and when I want to use I do; DATA[i] = do you know how to do similar but in two dimensions ? thanks -- http://mail.python.org/mailman/listinfo/python-list
Deleting lines from a file
Hi, I need to write a program which reads an external text file. Each time it reads, then it needs to delete some lines, for instance from second line to 55th line. The file is really big, so what do you think is the fastest method to delete specific lines in a text file ? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting lines from a file
and regardless of the speed, what do you think would be the best method to do this ? Michael Bentley wrote: > On Dec 17, 2007, at 5:34 AM, Horacius ReX wrote: > > > I need to write a program which reads an external text file. Each time > > it reads, then it needs to delete some lines, for instance from second > > line to 55th line. The file is really big, so what do you think is the > > fastest method to delete specific lines in a text file ? > > AFAIK, there really isn't much you can do to *speed* the reading and > writing of the large text file. But maybe you can avoid doing it too > much. If you must make many changes it might help to just keep a list > of lines to consider "deleted" -- and write the modified file out later. > > hth, > Michael > > --- > "I use tuples simply because of their mellifluous appellation." --Neil > Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Python; jump to a concrete line
Hi, sorry but after looking for information, I still did not get how, when reading a text file in python, can one jump to a concrete line and then read the different data (separated by spaces). In each line there is different number of columns so sometimes i get kind of "index out" error. Is there a better way to read the different data on each row and avoiding to know the exact number of columns ? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Extract a number from a complicated string
Hi, I have to read some data from a file, and on each block it always appears the followng string; xyz.vs.1-81_1 . It appears a lot of time with different numbers like; xyz.vs.1-81_1 xyz.vs.1-1234_1 xyz.vs.1-56431_1 and so on My problem is that I need to extract from this string the number. For instance in xyz.vs.1-81_1 I have to extract the number 81, and in xyz.vs.1-1234_1 I need to get the number 1234. What is the easiest way of doing this ? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Mix different C source files into a single one
Hi, I have a C program split into different source files. I am trying a new compiler and for some reason it only accepts a single source file. So I need to "mix" all my different C source files into a single one. Do you know about some type of python script able to do this kind of task ? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Look for a string on a file and get its line number
Hi, I have to search for a string on a big file. Once this string is found, I would need to get the number of the line in which the string is located on the file. Do you know how if this is possible to do in python ? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Look for a string on a file and get its line number
Hi, thanks for the help. Then I got running the following code;
#!/usr/bin/env python
import os, sys, re, string, array, linecache, math
nlach = 12532
lach_list = sys.argv[1]
lach_list_file = open(lach_list,"r")
lach_mol2 = sys.argv[2] # name of the lachand mol2 file
lach_mol2_file = open(lach_mol2,"r")
n_lach_read=int(sys.argv[3])
# Do the following for the total number of lachands
# 1. read the list with the ranked lachands
for i in range(1,n_lach_read+1):
line = lach_list_file.readline()
ll = string.split (line)
#print i, ll[0]
lach = int(ll[0])
# 2. for each lachand, print mol2 file
# 2a. find lachand header in lachand mol2 file (example; kanaka)
# and return line number
line_nr = 0
for line in lach_mol2_file:
line_nr += 1
has_match = line.find('kanaka')
if has_match >= 0:
print 'Found in line %d' % (line_nr)
# 2b. print on screen all the info for this lachand
# (but first need to read natoms and nbonds info)
#go to line line_nr + 1
ltr=linecache.getline(lach_mol2, line_nr + 1)
ll=ltr.split()
#print ll[0],ll[1]
nat=int(ll[0])
nb=int(ll[1])
# total lines to print:
# header, 8
# at, na
# b header, 1
# n
# lastheaders, 2
# so; nat + nb + 11
ntotal_lines = nat + nb + 11
# now we go to the beginning of the lachand
# and print ntotal_lines
for j in range(0,ntotal_lines):
print linecache.getline(lach_mol2, line_nr - 1
+ j )
which almost works. In the last "for j" loop, i expected to obtain an
output like:
sdsdsdsdsdsd
sdsdsfdgdgdgdg
hdfgdgdgdg
but instead of this, i get:
sdsdsdsdsdsd
sdsdsfdgdgdgdg
hdfgdgdgdg
and also the program is very slow. Do you know how could i solve
this ?
thanks
Tim Chase wrote:
> >> I have to search for a string on a big file. Once this string
> >> is found, I would need to get the number of the line in which
> >> the string is located on the file. Do you know how if this is
> >> possible to do in python ?
> >
> > This should be reasonable:
> >
> for num, line in enumerate(open("/python25/readme.txt")):
> > if "Guido" in line:
> > print "Found Guido on line", num
> > break
> >
> >
> > Found Guido on line 1296
>
> Just a small caveat here: enumerate() is zero-based, so you may
> actually want add one to the resulting number:
>
> s = "Guido"
> for num, line in enumerate(open("file.txt")):
> if s in line:
> print "Found %s on line %i" % (s, num + 1)
> break # optionally stop looking
>
> Or one could use a tool made for the job:
>
> grep -n Guido file.txt
>
> or if you only want the first match:
>
> sed -n '/Guido/{=;p;q}' file.txt
>
> -tkc
--
http://mail.python.org/mailman/listinfo/python-list
Complicated string substitution
Hi, I have a file with a lot of the following ocurrences: denmark.handa.1-10 denmark.handa.1-12344 denmark.handa.1-4 denmark.handa.1-56 ... distributed randomly in a file. I need to convert each of this ocurrences to: denmark.handa.1-10_1 denmark.handa.1-12344_1 denmark.handa.1-4_1 denmark.handa.1-56_1 so basically I add "_1" at the end of each ocurrence. I thought about using sed, but as each "root" is different I have no clue how to go through this. Any suggestion ? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
non-uniform string substituion
Hi, I have a file with a lot of the following ocurrences: denmark.handa.1-10 denmark.handa.1-12344 denmark.handa.1-4 denmark.handa.1-56 ... distributed randomly in a file. I need to convert each of this ocurrences to: denmark.handa.1-10_1 denmark.handa.1-12344_1 denmark.handa.1-4_1 denmark.handa.1-56_1 so basically I add "_1" at the end of each ocurrence. I thought about using sed, but as each "root" is different I have no clue how to go through this. Any suggestion ? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Mysterious EOFError
Hi,
I'm executing a python script as a cron job. When I run it myself from
the command line it works, but when cron executes it I get an EOFError:
File "/home/rex/cronscript.py", line 6, in ?
level = int(raw_input("hello?"))
EOFError: EOF when reading a line
It's not the last line of the file.
When I run it as root from the command line I don't get any errors.
Any ideas?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Mysterious EOFError
Thanks. Do you know of a solution to this? I tried the following, which
I found on this newsgroup:
#
lines = open(sys.argv[1]).readlines()
#
sys.stdin = open('/dev/tty')
a = raw_input('Prompt: ')
#
sys.stdin = os.fdopen(3)
a = raw_input('Prompt: ')
#
What I want to do is execute a scheduled task that prompts me for
something and allows me to enter it and have it stored somewhere. I'm
on Ubuntu Linux.
Thanks in advance!
Steven D'Aprano wrote:
> On Sat, 08 Apr 2006 23:07:54 -0700, Rex Eastbourne wrote:
>
> > Hi,
> >
> > I'm executing a python script as a cron job. When I run it myself from
> > the command line it works, but when cron executes it I get an EOFError:
> >
> > File "/home/rex/cronscript.py", line 6, in ?
> > level = int(raw_input("hello?"))
> > EOFError: EOF when reading a line
>
>
> Because raw_input is waiting for input from the user. I assume that when
> cron runs a Python script, and there is no actual human user to enter a
> string in response to raw_input, it raises a EOF error.
>
> Written in the docs:
>
> http://docs.python.org/lib/module-exceptions.html
>
>
> exception EOFError
> Raised when one of the built-in functions (input() or raw_input())
> hits an end-of-file condition (EOF) without reading any data. (N.B.:
> the read() and readline() methods of file objects return an empty
> string when they hit EOF.)
>
>
> --
> Steven.
--
http://mail.python.org/mailman/listinfo/python-list
