A way of checking if a string contains a number
Hey
I'm new to python, but I have used a fair bit of C and Perl
I found Perls regex's to be very easy to use however I don't find
Pythons regexes as good.
All I am trying to do is detect if there is a number in a string.
I am reading the string from an excel spread sheet using the xlrd
module
then I would like to test if this string has a number in it
ie.
import xlrd
import re
doesHaveNumber = re.compile('[0-9]')
string1 = ABC 11
regularExpressionCheck = doesHaveNumber.search(string1)
This will get the right result but then I would like to use the result
in an IF statement and have not had much luck with it.
if regularExpressionCheck != "None"
print "Something"
the result is that it prints every line from the spreadsheet to output
but I only want the lines from the spreadsheet to output.
Is there a way I can drop the regular expression module and just use
built in string processing?
Why si the output from checks in teh re module either "None" or some
crazy memory address? Couldn't it be just true or false?
--
http://mail.python.org/mailman/listinfo/python-list
Re: A way of checking if a string contains a number
Thanks worked Perfectly
On Dec 13, 9:32 am, [EMAIL PROTECTED] wrote:
> On Dec 12, 3:10 pm, Hamish <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > Hey
>
> > I'm new to python, but I have used a fair bit of C and Perl
>
> > I found Perls regex's to be very easy to use however I don't find
> > Pythons regexes as good.
>
> > All I am trying to do is detect if there is a number in a string.
>
> > I am reading the string from an excel spread sheet using the xlrd
> > module
>
> > then I would like to test if this string has a number in it
>
> > ie.
> > import xlrd
> > import re
>
> > doesHaveNumber = re.compile('[0-9]')
> > string1 = ABC 11
>
> > regularExpressionCheck = doesHaveNumber.search(string1)
>
> > This will get the right result but then I would like to use the result
> > in an IF statement and have not had much luck with it.
>
> > if regularExpressionCheck != "None"
> > print "Something"
>
> > the result is that it prints every line from the spreadsheet to output
> > but I only want the lines from the spreadsheet to output.
>
> > Is there a way I can drop the regular expression module and just use
> > built in string processing?
>
> > Why si the output from checks in teh re module either "None" or some
> > crazy memory address? Couldn't it be just true or false?
>
> None isn't a string, None is a special object under Python. Functions
> that don't return anything actually return the None value. In a
> boolean context, None is false.
>
> Python objects can be used in a boolean context, such as an if-
> statement. Empty sequences (such as tuples, strings, and lists),
> None, 0, and 0.0 are treated as False. Everything else is usually
> treated as "True". If a class defines a __len__ or __nonzero__
> method, those methods are called to determine if an instance is True
> or False. Otherwise, all objects are True.
>
> There's also only one None object, so identity testing is the pythonic
> idiom for testing against None.
>
> So, your check needs to be:
> if regularExpressionCheck is not None:
> print "Something"
>
> or, even more simply:
> if regularExpressionCheck:
> print "Something"
>
> I recommend that you peruse a Python tutorial or two. These are
> fairly basic attributes of the Python language. If you're using
> regular expressions, you'll want to be aware of how to make raw
> strings to help you out.
>
> --Jason- Hide quoted text -
>
> - Show quoted text -
--
http://mail.python.org/mailman/listinfo/python-list
Python stopped installing packages
Hi, Recently I’ve been trying to code a Discord bot in Python 3.6.2, then I realised that some features of discord.py were only available in Python 3.7+ (as seen here on the right near the top https://docs.python.org/3/library/asyncio.html), so I downloaded 3.7.2. After correctly changing the environmental variables to have Python 3.7.2 before Python 3.6.2, I tried installing (for installing I was using cmd ‘pip install discord.py’, I’m not aware of any other way to install packages) discord.py onto Python 3.7.2, but after a few seconds there would be a whole page of red error text (attached), then it would say successfully installed. I tried importing it in code, but it would return errors implying it was incorrectly installed. I asked one of my friends for some help. He suggested uninstalling Python 3.6.2 and 3.7.2 and reinstalling Python 3.7.2. I thought this was a pretty good idea so I did it. Discord.py still refuses to be installed. I tried installing some of the packages I had in 3.6.2, but they had the same sort of problem. I’ve tried running the installer to repair the files, but that didn’t work. I would appreciate if you could help me. I got discord.py from here: https://github.com/Rapptz/discord.py I’ve tried the 3 commands in the Installing section and I’ve tried pip install discord.py. Thanks, Hamish -- https://mail.python.org/mailman/listinfo/python-list
Re: Oreilly CodeZoo
A sexy design? But yes, there are quite a few out there. -- http://mail.python.org/mailman/listinfo/python-list
Verify server certificate in HTTPS transaction
Hi, I'm fetching some files over HTTPS from Python and I want to verify the server certificate. (Not just the name etc provided in certificate.) How can I get access to this information? urllib2 doesn't seem to provide it. Even a raw SSL socket only appears to provide access to the CN, OU etc in string form (not the raw certificate). I tried pycurl, which allows you to setopt(pycurl.SSL_VERIFYPEER) and VERIFYHOST, but the getinfo(pycurl.SSL_VERIFYRESULT) call always returns 0. Perhaps it's unimplememented? I couldn't get the M2Crypto API documentation to generate; perhaps it allows it. TLS Lite on to of M2Crypto? Something else again? Thanks Hamish -- http://mail.python.org/mailman/listinfo/python-list
Re: Integer division
[EMAIL PROTECTED] wrote: > Hello all, > I have two integers and I want to divide one by another, and want to > get an integer result which is the higher side whenever the result is > a fraction. > 3/2 => 1 # Usual behavior > some_func(3, 2) => 2 # Wanted > > Any easier solution other than int(math.ceil(float(3)/2)) The normal solution is to add (divisor-1) to the dividend before division. Ie ceil(3/2) = floor((3+(2-1))/2) = 2. Correct. But ceil(4/2) = floor((4+(2-1))/2) = 2 also. Correct. Hamish -- http://mail.python.org/mailman/listinfo/python-list
Re: Integer division
[EMAIL PROTECTED] wrote: > On Jun 7, 2:15 pm, Hamish Moffatt <[EMAIL PROTECTED]> wrote: >> [EMAIL PROTECTED] wrote: >>> Hello all, >>> I have two integers and I want to divide one by another, and want to >>> get an integer result which is the higher side whenever the result is >>> a fraction. >>> 3/2 => 1 # Usual behavior >>> some_func(3, 2) => 2 # Wanted >>> Any easier solution other than int(math.ceil(float(3)/2)) >> The normal solution is to add (divisor-1) to the dividend before division. >> >> Ie ceil(3/2) = floor((3+(2-1))/2) = 2. Correct. >> But ceil(4/2) = floor((4+(2-1))/2) = 2 also. Correct. > > What about this? > >>>> def div_ceil(a, b): > ... if a%b: > ... return ((a/b)+1) > ... else: > ... return (a/b) Yes, although it's not as short or as fast (probably as my version): def div_ceil(a, b): return ((a+(b-1))/b) Hamish -- http://mail.python.org/mailman/listinfo/python-list
SafeConfigParser can set unsafe values
SafeConfigParser is supposed to be safer than ConfigParser, but calling
set with a string value containing '%' generates exceptions when you
get() it back.
Python 2.5.1 (r251:54863, Apr 25 2007, 21:31:46)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import configparser
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named configparser
>>> import ConfigParser
>>>
>>> x=ConfigParser.SafeConfigParser()
>>> x.add_section('test')
>>> x.set('test', 'a', 'hi%there')
>>> x.get('test', 'a')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.5/ConfigParser.py", line 525, in get
return self._interpolate(section, option, value, d)
File "/usr/lib/python2.5/ConfigParser.py", line 593, in _interpolate
self._interpolate_some(option, L, rawval, section, vars, 1)
File "/usr/lib/python2.5/ConfigParser.py", line 634, in _interpolate_some
"'%%' must be followed by '%%' or '(', found: %r" % (rest,))
ConfigParser.InterpolationSyntaxError: '%' must be followed by '%' or
'(', found: '%there'
ConfigParser does not do this:
>>> y=ConfigParser.ConfigParser()
>>> y.add_section('test')
>>> y.set('test', 'a', 'hi%there')
>>> y.get('test', 'a')
'hi%there'
Should SafeConfigParser.set() be escaping automatically?
Hamish
--
http://mail.python.org/mailman/listinfo/python-list
Re: SafeConfigParser can set unsafe values
Matimus wrote: >> Should SafeConfigParser.set() be escaping automatically? > > It seems like that would be a nice feature. However, may I offer up > that if you are setting an option and then later on getting that value > back in the same program, you probably should have used some other > storage mechanism in the first place. That is, you shouldn't store > values needed during the runtime of your program in a ConfigParser > instance. I agree, but that was a trivial example to demonstrate the problem. Writing the file out to disk writes it exactly as set(), causing a get() to fail just the same later. > While I think you have technically pointed out a potential bug, I'm > not sure why it matters. Such a bug only comes about for (IMHO) flawed > use cases. Sorry, that's incorrect. Hamish -- http://mail.python.org/mailman/listinfo/python-list
Re: SafeConfigParser can set unsafe values
Matimus wrote:
>> I agree, but that was a trivial example to demonstrate the problem.
>> Writing the file out to disk writes it exactly as set(), causing a get()
>> to fail just the same later.
>
> No... The above statement is not true.
Yes, it is. Whatever you set gets written out directly. Your example
proves this:
> cp.set("sect","opt","hello%world")
> cp.write(sys.stdout)
> [/code]
>
> Produces this output:
> [sect]
> opt = hello%world
Then when you get() this value later, it fails.
> The write method never calls get. However, when you read the file that
> was output by the above code using .get(...) will raise an error. You
> can avoid that error by setting the optional 'raw' parameter to True.
But then you have disabled substitution, which is not the same thing! I
don't necessarily want to disable substitution, I just want transparent
handling of lone %s.
Since SafeConfigParser.get() is fussy about the format of interpolation
instructions, SafeConfigParser.set() can safely know when you're not
trying to use them and escape lone percents.
To summarise: set() should not set something which get() will ALWAYS
fail on!
Hamish
--
http://mail.python.org/mailman/listinfo/python-list
Re: Syslog
greg wrote: > Could anyone tell me how I could syslog to a specific log (e.g. /var/ > log/daemon.log, /var/log/syslog.log...)? > > Thanks very much in advance! It's up to your syslogd to route messages into particular files, based on their facility and/or priority. Check out /etc/syslog.conf or equivalent on your system. Hamish -- http://mail.python.org/mailman/listinfo/python-list
Re: libgmail failure
On Aug 21, 5:07 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> Hey all,
>
> I've been usinglibgmailto send out automated notification emails for
> my company's nightly regression testing. Last night these emails
> started failing, though the python code has not changed. I updated to
> the latestlibgmail, but that isn't helping. I've logged in to the
> email account directly, and the account is still working fine.
>
> The error I get is "HTTP Error 400: Bad Request" when using
> gmailAccount.login(). This doesn't throw an exception, just prints
> the error. The code crashes outright when it tries to send mail.
>
> This code has been up and running for several months and just started
> failing last night. Does anyone have an idea what's going on?
>
> The code and error follow (fairly short :-)
>
> Thanks much,
> James
>
> Code:
> ---
> def send(TO_LIST,SUBJECT,MESSAGE):
> GA =libgmail.GmailAccount("[EMAIL PROTECTED]","xxx")
> try:
> print "Logging in"
> GA.login()
> exceptlibgmail.GmailLoginFailure:
> print "\nLogin failed. (Wrong username/password?)"
> else:
> print "Log in successful.\n"
> for RX in TO_LIST:
> MSG =libgmail.GmailComposedMessage(RX,SUBJECT,MESSAGE)
> if GA.sendMessage(MSG):
> print "Message successfully sent to `%s` ." % RX
> else:
> print "Could not send message."
> ---
>
> Output:
> ---
> Logging in
> HTTP Error 400: Bad Request
> Log in successful.
>
> No messages found
> Traceback (most recent call last):
> File "C:\projects\physware\testCases\PythonTestScripts
> \SendEmail.py", line 58, in
> main()
> File "C:\projects\physware\testCases\PythonTestScripts
> \SendEmail.py", line 55, in main
> send(TO_LIST,SUB,MSG)
> File "C:\projects\physware\testCases\PythonTestScripts
> \SendEmail.py", line 39, in send
> if GA.sendMessage(MSG):
> File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py",
> line 588, in sendMessage
> U_ACTION_TOKEN: self._getActionToken(),
> File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py",
> line 563, in _getActionToken
> at = self._cookieJar._cookies[ACTION_TOKEN_COOKIE]
> KeyError: 'GMAIL_AT'
> ---
I believe I've found a (temporary) fix in this forum thread:
http://www.castlecops.com/p984588-HTTP_Error_400_when_using_gknujon.html
Pasted here for posterity;
---
Edit the libgmail.py file.
In the function
def login(self)
change the following text:
Code:
try:
link = re.search(RE_PAGE_REDIRECT, pageData).group(1)
redirectURL = urllib.unquote(link)
to add the extra line:
Code:
try:
link = re.search(RE_PAGE_REDIRECT, pageData).group(1)
redirectURL = urllib.unquote(link)
redirectURL = redirectURL.replace('\\x26','&')
---
Must have been some small change in gmail's redirect that put it off.
--
http://mail.python.org/mailman/listinfo/python-list
Unbuffered mode
Hi,
The man page for python says:
"-u Force stdin, stdout and stderr to be totally unbuffered."
However, when I try:
$ ssh localhost python -u
print 'hello, world'
[^D]
hello, world
$
Nothing happens until I send that EOF. I'm pretty sure it's not SSH
that's buffering because when I try:
$ ssh localhost bash
echo 'hello, world'
hello, world
[^D]
$
The 'hello, world' comes back immediately (I don't need to send the EOF).
I've also tried:
$ ssh localhost python -u
import sys
sys.stdout.write('hello, world\n')
sys.stdout.flush()
[^D]
hello, world
$
Again, nothing happens until I send the EOF. How can I get Python to
run over SSH unbuffered?
Thanks,
Hamish
--
http://mail.python.org/mailman/listinfo/python-list
Re: Unbuffered mode
Further to my query about trying to make Python run unbuffered, I have
discovered that a SyntaxError seems to cause Python to close its SSH
connection:
$ ssh localhost python -u
,
File "", line 1
,
^
SyntaxError: invalid syntax
$
Whereas a different sort of error (e.g. NameError) does not:
$ ssh localhost python -u
pront
[^D]
Traceback (most recent call last):
File "", line 1, in
NameError: name 'pront' is not defined
$
Can anyone tell me why?!
Thanks,
Hamish
On Feb 13, 2008 1:12 AM, Hamish Allan <[EMAIL PROTECTED]> wrote:
> Hi,
>
> The man page for python says:
>
> "-u Force stdin, stdout and stderr to be totally unbuffered."
>
> However, when I try:
>
> $ ssh localhost python -u
> print 'hello, world'
> [^D]
> hello, world
> $
>
> Nothing happens until I send that EOF. I'm pretty sure it's not SSH
> that's buffering because when I try:
>
> $ ssh localhost bash
> echo 'hello, world'
> hello, world
> [^D]
> $
>
> The 'hello, world' comes back immediately (I don't need to send the EOF).
>
> I've also tried:
>
> $ ssh localhost python -u
> import sys
> sys.stdout.write('hello, world\n')
> sys.stdout.flush()
> [^D]
> hello, world
> $
>
> Again, nothing happens until I send the EOF. How can I get Python to
> run over SSH unbuffered?
>
> Thanks,
> Hamish
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Unbuffered mode
Sorry to reply to myself again, but I think I now know the answer and
wish to post it for the archives.
Python run without '-i', if not sys.stdin.isatty(), expects to read a
whole script before doing anything else (presuming to be reading it
from a pipe). Therefore syntax errors are fatal, but otherwise nothing
is executed until EOF.
So the answer to my question is to run:
$ ssh localhost python -ui
Best wishes,
Hamish
On Feb 13, 2008 4:20 PM, Hamish Allan <[EMAIL PROTECTED]> wrote:
> Further to my query about trying to make Python run unbuffered, I have
> discovered that a SyntaxError seems to cause Python to close its SSH
> connection:
>
> $ ssh localhost python -u
> ,
> File "", line 1
> ,
> ^
> SyntaxError: invalid syntax
> $
>
> Whereas a different sort of error (e.g. NameError) does not:
>
> $ ssh localhost python -u
> pront
> [^D]
> Traceback (most recent call last):
> File "", line 1, in
> NameError: name 'pront' is not defined
> $
>
> Can anyone tell me why?!
>
> Thanks,
> Hamish
>
>
> On Feb 13, 2008 1:12 AM, Hamish Allan <[EMAIL PROTECTED]> wrote:
> > Hi,
> >
> > The man page for python says:
> >
> > "-u Force stdin, stdout and stderr to be totally unbuffered."
> >
> > However, when I try:
> >
> > $ ssh localhost python -u
> > print 'hello, world'
> > [^D]
> > hello, world
> > $
> >
> > Nothing happens until I send that EOF. I'm pretty sure it's not SSH
> > that's buffering because when I try:
> >
> > $ ssh localhost bash
> > echo 'hello, world'
> > hello, world
> > [^D]
> > $
> >
> > The 'hello, world' comes back immediately (I don't need to send the EOF).
> >
> > I've also tried:
> >
> > $ ssh localhost python -u
> > import sys
> > sys.stdout.write('hello, world\n')
> > sys.stdout.flush()
> > [^D]
> > hello, world
> > $
> >
> > Again, nothing happens until I send the EOF. How can I get Python to
> > run over SSH unbuffered?
> >
> > Thanks,
> > Hamish
> >
>
--
http://mail.python.org/mailman/listinfo/python-list
getting caller
so I'm trying to wrap some functionality around execfile but don't want to modify the way it works. specifically when you call execfile, it automatically grabs globals and locals from the frame the execfile exists in. so if I wrap execfile in a function, I need a way to reliably get at the calling frame. what I want to know is - is it *ALWAYS* true that: inspect.getouterframes( inspect.currentframe() )[ 1 ][ 0 ] will return me the frame that called execfile in the first place? I can't think of a way that this wouldn't be the case, but I'm not 100% sure that assertion is valid. -- http://mail.python.org/mailman/listinfo/python-list
type conversion
sometimes I want to be able to initialize an instance with a variety of different data types. as an obvious example I might want to initialize a 4x4 matrix with either 16 floats, a list/tuple or 16 floats, another matrix or a quaternion. is there any other way to do it other than putting case statements in the __init__ method of the class, or having a Matrix.FromQuaternion( quat )? thx -- http://mail.python.org/mailman/listinfo/python-list
RE: type conversion
>> You could also use a dict with type:method key/value pairings. This is >> closer to a switch/case than an if...elif chain is. of course, that's a great idea... thanks. -- http://mail.python.org/mailman/listinfo/python-list
RE: type conversion
I actually have no idea what ur talking about... aren't conversations threaded by subject? -Original Message- From: [email protected] [mailto:[email protected]] On Behalf Of r Sent: Friday, January 02, 2009 12:12 PM To: [email protected] Subject: Re: type conversion On Jan 2, 1:46 pm, Robert Kern wrote: > r wrote: > > On Jan 1, 4:40 pm, Robert Kern wrote: > >> Hamish McKenzie wrote: > >>> sometimes I want to be able to initialize an instance with a variety of > >>> different data types. > >>> as an obvious example I might want to initialize a 4x4 matrix with either > >>> 16 floats, a list/tuple or 16 floats, another matrix or a quaternion. > >>> is there any other way to do it other than putting case statements in the > >>> __init__ method of the class, or having a Matrix.FromQuaternion( quat )? > >> I recommend keeping the __init__() as dumb as possible. Ideally, it should > >> just > >> assign to attributes. I would add a from() classmethod for each > >> that > >> I wanted to support. If I really wanted an all-singing, all-dancing > >> initialization method, I would add another classmethod that would just > >> dispatch > >> to the appropriate type-specific classmethod. I prefer classmethods to > >> plain > >> functions because I can subclass. > > >> -- > >> Robert Kern > > >> "I have come to believe that the whole world is an enigma, a harmless > >> enigma > >> that is made terrible by our own mad attempt to interpret it as though > >> it had > >> an underlying truth." > >>-- Umberto Eco > > > Why are you busting into this thread? > > Are you talking to me, or Hamish, who (presumably unintentionally) responded > to > a message instead of making a new thread? > > If you want to suggest that one should have more care about starting new > threads, that's fine, but please do not jump to the conclusion that there is > malintent. And don't chastise people for not being as rude as you. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." >-- Umberto Eco I am not so much chastising Hamish as i am Steven, Steven knows better than this BS, and has preached to so many people about off topic post that my ears are bleeding from his incessant rambling about it. Now, he goes and does what he complains about s much. I'm just calling him on it thats all. I can't speak for the other responders because i know of none of them. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
python bug when subclassing list?
I want to write a Vector class and it makes the most sense to just subclass list. I also want to be able to instantiate a vector using either: Vector( 1, 2, 3 ) OR Vector( [1, 2, 3] ) so I have this: class Vector(list): def __new__( cls, *a ): try: print a return list.__new__(cls, a) except: print 'broken' return list.__new__(cls, list(a)) doing Vector( 1, 2, 3 ) on this class results in a TypeError - which doesn't seem to get caught by the try block (ie "broken" never gets printed, and it never tries to I can do pretty much the exact same code but inheriting from tuple instead of list and it works fine. is this a python bug? or am I doing something wrong? thanks, -h. -- http://mail.python.org/mailman/listinfo/python-list
python bug when subclassing list?
I want to write a Vector class and it makes the most sense to just subclass list. I also want to be able to instantiate a vector using either: Vector( 1, 2, 3 ) OR Vector( [1, 2, 3] ) so I have this: class Vector(list): def __new__( cls, *a ): try: print a return list.__new__(cls, a) except: print 'broken' return list.__new__(cls, list(a)) doing Vector( 1, 2, 3 ) on this class results in a TypeError - which doesn't seem to get caught by the try block (ie "broken" never gets printed, and it never tries to I can do pretty much the exact same code but inheriting from tuple instead of list and it works fine. is this a python bug? or am I doing something wrong? thanks, -h. -- http://mail.python.org/mailman/listinfo/python-list
inheritance question...
I have this class: class Vector(object): TOL = 1e-5 def __eq__( self, other, tolerance=TOL ): print tolerance shortened for clarity obviously. so I want to subclass this class like so: class BigVector(Vector) TOL = 100 for example if I was working with large vectors which I knew would never be very close hence the large tolerance. this doesn't work however - the TOL class variable, while overridden in BigVector, is still using the Vector.TOL variable in the __eq__ method. which kinda makes sense to a certain degree, but how do I get the behaviour where doing: BigVector().__eq__( otherVec ) prints 100 instead of 1e-5? does this question make sense? not sure how clearly I'm phrasing my question... any of you guys python experts? I *could* do this, but its ugly: class Vector(object): TOL = 1e-5 def __eq__( self, other, tolerance=None ): if tolerance is None: tolerance = self.TOL print tolerance -- http://mail.python.org/mailman/listinfo/python-list
str class inheritance prob?
so I'm trying to create a class that inherits from str, but I want to
run some code on the value on object init. this is what I have:
class Path(str):
def __init__( self, path ):
clean = str(path).replace('\\','/')
while clean.find('//') != -1:
clean = clean.replace('//','/')
print 'cleaned on init:\t',clean
self = clean
so clearly the clean variable is what I want value of the string to be,
but that's decidedly not the case. so running this:
a=Path('path///with\\nasty/crap_in_it/')
print a
gives me this:
cleaned on init: path/with/nasty/crap_in_it/
path///with\nasty/crap_in_it/
what gives? what am I doing wrong, and can I do what I'm trying to
here?
thanks.
--
http://mail.python.org/mailman/listinfo/python-list
how to read stdout without blocking
I need to run a cmd line app from python whose run time can vary from a fraction of a second to minutes. I need to be able to tell whether the process is still waiting, or whether it has stalled - and this is farily easily done by keeping an eye on whether its writing to stdout or not. The process under working conditions will write to stdout fairly regularly. So I want to bail out waiting for the process if it is no longer writing to stdout, but whenever I read stdout the script blocks and doesn't return until the process has finished. This is under windows, python 2.5. Can anyone help? The code I'm using is below. import subprocess import time TIMEOUT_PERIOD = 5 #timeout period in seconds def run( *args ): cmdStr = 'somePotentiallyLengthyCmdHere' try: proc = subprocess.Popen( cmdStr, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) except OSError: return False startTime = time.clock() stdoutAccum = [] stderrAccum = [] hasTimedOut = False while True: ret = proc.poll() newStdout = proc.stdout.read() newStderr = proc.stderr.read() print 'waiting...' stdoutAccum += newStdout stderrAccum += newStderr #if the proc has terminated, deal with returning appropriate data if ret is not None: if hasTimedOut: if callable( RETURNED_CALLBACK ): try: RETURNED_CALLBACK( *args ) except: pass return stdoutAccum + stderrAccum #if there has been new output, the proc is still alive so reset counters if newStderr or newStdout: startTime = time.clock() #make sure we haven't timed out curTime = time.clock() if curTime - startTime > TIMEOUT_PERIOD: hasTimedOut = True -- http://mail.python.org/mailman/listinfo/python-list
Express thanks
I wanted to give a shout out to the wonderfully passionate contributions to python I've witnessed following this and other mailing lists over the last little bit. The level of knowledge and willingness to help I've seen are truly inspiring. Super motivating. Probably the wrong forum for such a message but what the hey. Hamish -- -- https://mail.python.org/mailman/listinfo/python-list
