Python and MySQL server

2005-07-14 Thread Unknown
Python 2.4
Linux kernel 2.6.12

Hi,

1. How do I make the following statement to search for all Strings I
input from console?

for example, with the code below I need to enter %hello world% (yeah,
including the % symbols) to find all entries for hello world on the
tableName. But I want to set the % symbols on the code itself so I don't
have to input manually the % at the prompt.

searchWhat = raw_input ('Search for : ')
cursor.execute('select * from tableName where contentField like
%s',(searchWhat))

2. I'm entering data by copying and pasting. Much of the text is in
multiple lines and some formated sections such as paragraphs,
indentations, double lines and what not.

How do I enter keep the formated text intact if entering from console? Now
it loses all formatting and I have to copy and paste text line by line
because it won't take the multiple lines.

insertEntryId = raw_input('New Entry ID: ')
insertEntryContent = raw_input('New Entry Content: ')
insertEntryCategory = raw_input('New Category: ')

cursor.execute('insert into tableName values (%s,%s,%s)',
(insertEntryId,insertEntryContent,insertEntryCategory))

Thanks, Any help is appreciate it.

Mr. Frodo

-- 
http://mail.python.org/mailman/listinfo/python-list


error processing variables

2005-09-09 Thread Unknown
PROBLEM: for some reason, the variables won't work outside the function.
I tried fix it by converting the variables to str and unicode and still no
joy.
 The only way it works is by typing each source and
 destination file by hand on the shutil.copy2() method.
 Or by specifying the functions *inside* the function itself.

Any ideas?

ERROR:
Traceback (most recent call last):
  File "data/scripts/wifi.py", line 76, in main
toHPU()
  File "data/scripts/wifi.py", line 32, in toHPU
s.copy2(toHPU,wlan)
  File "/usr/lib/python2.4/shutil.py", line 92, in copy2
copyfile(src, dst)
  File "/usr/lib/python2.4/shutil.py", line 41, in copyfile
if _samefile(src, dst):
  File "/usr/lib/python2.4/shutil.py", line 31, in _samefile
return os.path.samefile(src, dst)
  File "/usr/lib/python2.4/posixpath.py", line 218, in samefile
s1 = os.stat(f1)
TypeError: coercing to Unicode: need string or buffer, function found


CODE:

import shutil

#variables
s = shutil

toHPU = "/etc/sysconfig/network/toHPU.wifi"
wlan = "/etc/sysconfig/network/ifcfg-wlan-id-00:0e:38:88:ba:6d"
toAnyWifi = "/etc/sysconfig/network/toAny.wifi"
wired = "/etc/sysconfig/network/ifcfg-eth-id-00:0b:db:1b:e3:88"  


def toHPU():


s.copy2(toHPU,wlan) 
s.copy2(toAnyWifi,wired)
 
#end

#execute function
toHPU()

---


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-12 Thread unknown
On Mon, 11 Nov 2013 14:26:46 -0800, Matt wrote:

> So I want to take the file, "desktop/test.txt" and write it to
> "desktop/newfolder/test.txt". I tried the below script, and it gave me:
> "IOError: [Errno 2] No such file or directory: 'desktop/%s.txt'". Any
> suggestions would be great.
> 
> 
> 
> def firstdev(file):
>   in_file = open("desktop/%s.txt") % file indata = in_file.read()
>   out_file = open("desktop/newfolder/%s.txt", 'w') % file
>   out_file.write(indata)
>   out_file.close()
>   in_file.close()
>   
> firstdev("test")

would it not be more efficient and less error prone to use the os module 
to copy the file rather than manually reading & re-writing it (unless of-
course you intend to expand this in future to process the data first)?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-12 Thread unknown
On Tue, 12 Nov 2013 11:24:02 +0100, Peter Otten wrote:

> unknown wrote:
> 
>> On Mon, 11 Nov 2013 14:26:46 -0800, Matt wrote:
>> 
>>> So I want to take the file, "desktop/test.txt" and write it to
>>> "desktop/newfolder/test.txt". I tried the below script, and it gave
>>> me:
>>> "IOError: [Errno 2] No such file or directory: 'desktop/%s.txt'". Any
>>> suggestions would be great.
>>> 
>>> 
>>> 
>>> def firstdev(file):
>>> in_file = open("desktop/%s.txt") % file indata = in_file.read()
>>> out_file = open("desktop/newfolder/%s.txt", 'w') % file
>>> out_file.write(indata)
>>> out_file.close()
>>> in_file.close()
>>> 
>>> firstdev("test")
>> 
>> would it not be more efficient and less error prone to use the os
>> module to copy the file rather than manually reading & re-writing it
>> (unless of-
>> course you intend to expand this in future to process the data first)?
> 
> Hmm, I don't see a suitable function in os -- but there is
> 
> shutil.copy()

that's what i get for posting on the fly without checking first but i 
think the principle holds.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Implementing a multivibrator function with python

2013-11-12 Thread unknown
On Tue, 12 Nov 2013 06:44:05 -0800, JL wrote:

> I am actually running python on raspberry pi. The trigger event is a
> button-press.
> 
> On Monday, November 11, 2013 6:56:03 PM UTC+8, Dave Angel wrote:
>> On Mon, 11 Nov 2013 01:41:58 -0800 (PST), JL 
>> 
>> wrote:
>> 
>> > - If the event happens again before the 5secs expire, the high
>> 
>> duration will be extended by another 5 secs. This works like a
>> 
>> retriggerable multivibrator for those who are into electronics.
>> 
>> 
>> 
>> More precisely a retriggerable monostable multivibrator.
>> 
>> 
>> 
>> The question makes little sense unless you're running in an event
>> 
>> driven environment, such as a gui. Name the environment and somebody
>> 
>> can probably help.
>> 
>> 
>> 
>> --
>> 
>> DaveA

How critical is the output pulse time?
is it a state that can be polled to regularly & changed if the timeout 
has been exceeded or does it need to switch in the background?

if you need to trigger & switch in the background you will probably need 
to start playing with threads or multiprocessing.

greater detail on what you are trying to achieve project wise may assist 
here
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-14 Thread unknown
On Thu, 14 Nov 2013 14:29:41 +1100, Chris Angelico wrote:

> On Thu, Nov 14, 2013 at 2:22 PM, Rick Johnson
>  wrote:
>> Yeah, a "global" keyword that extends access ONLY as far as module
>> level scope -- hardly a *true* global.
> 
> I have yet to see any language that gives true globals. At very best,
> they're just process-wide! Honestly. How am I supposed to write code
> that accesses variables running on my New York server?
> 
> Now, of course, if I had a server on Mars, that would be completely
> different. They're only globals, after all.
> 
> ChrisA

+ networking computers on Mars is impossible (with TCP/IP at least)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Invalid syntax with print "Hello World"

2013-11-14 Thread unknown
On Thu, 14 Nov 2013 07:05:08 -0800, johannes.gunz97 wrote:

> Am Donnerstag, 12. März 2009 07:57:11 UTC+1 schrieb Henrik Bechmann:
>> obviously total mewbiew:
>> 
>> My first program in Python Windows
>> 
>> print "Hello World"
>> 
>> I select Run/Run Module and get an error:
>> 
>> Syntax error, with the closing quote highlighted.
>> 
>> Tried with single quotes as well. Same problem.
>> 
>> Can someone explain my mistake?
>> 
>> Thanks,
>> 
>> - Henrik
> 
> thanx

which version of python?
if V3.X then you need print ('Hello World')
as print has changed from a statement to a function.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Immediate requirement - Sr. Business Analyst for Pricewaterhouse Coopers (PwC) in Tampa, FL.

2013-11-07 Thread unknown
On Thu, 07 Nov 2013 11:45:24 -0800, parker.svksystems wrote:

> Hi,
> 
> Immediate requirement - Sr. Business Analyst for Pricewaterhouse Coopers
> (PwC) in Tampa, FL.
> 
>  Sr. Business Analyst – BA - # 900663
>  
> Start: Immediate Duration: 9 - 12 Months
>  
>  
> Here is the job description for the new position at PwC in Tampa, FL.
>  
> This role is responsible for overseeing Business Analysts or having
> individual responsibility for applying analytical skills to determine
> and document accurate business requirements; presenting these
> requirements in a manner that is concise, measurable and flexible enough
> to meet project and stakeholder needs.
>  
> This person should have exceptional verbal and written communication
> skills. This role liaises with IT, Demand, and Business Stakeholders in
> order to understand the structure, policies and operations of the
> business and to recommend solutions that will enable the Business
> Stakeholders to achieve their goal(s). This role works with the Project
> Manager and Relationship Manager to manage the stakeholders'
> expectations, ensures that the solution is within the expressed business
> need, and provides business analysis work progress and other relevant
> information that may affect the project scope, schedule and cost. This
> role also will work closely with the Test Lead.
>  
> Must have at least 5 years’ experience in the following areas:
> • Knowledge with the SDLC activities expected to develop custom
> developed and packaged applications with exposure to Business Process
> Modeling and/or Re-engineering is preferred.
> • Also Business Use Case Development, Business Rules
> Development, Use Case Driven Requirement Methods, UML and RUP knowledge
> is preferred.
>  
>  
> Candidates should have knowledge in Enterprise Application Portfolio
> Strategy/Development. Experience in Agile development, Team Foundation
> Server, including entering User Stories, Bugs, Enhancements, Burndown
> and working with off shore resources. Experience with stfSoft
>  
> Deep experience with the full Microsoft BI stack, including: SQL Server,
> SSAS, SSRS, SSIS, SharePoint,, .NET (for any architects) Strong business
> analysis skills, facilitation skills and a thorough understanding of
> analysis deliverables (including UML artifacts and how they relate to
> the development process). Demonstrated technical and leadership
> expertise in application development and project management in
> distributed systems and web technologies. Strong technology acumen and
> track record of hands-on implementations across multiple technologies.
>  
> Ability to translate technical data and concepts and communicate them to
> non-technical personnel. Strong skills in both technology and business
> domains, creative and practical in managing the relationship between the
> two. Strong background in implementing enterprise initiatives on a large
> scale. Undergraduate Degree (e.g., BA, BS) or equivalent experience
> 
> 
> Thanks and Regards Petter Parker Technical Recruiter 11465 Johns Creek
> Pkway, Johns Creek, GA 30097 Phone # 678-824-7785 par...@svksystems.com 
> || krishnacarrires.svksystems.com (Gtalk) || petter.parker123  (Skype)
> || www.svksystems.com (Company mail ID)
> 
> 
> Microsoft Certified Partner | Oracle Certified Partner | E-Verified
> Company

Nicos is your guy, nicos.gr...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To whoever hacked into my Database

2013-11-08 Thread unknown
> 
> You have demonstrated significant difficulties in social interaction and
> behavior.

Pot - Kettle
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To whoever hacked into my Database

2013-11-08 Thread unknown
On Fri, 08 Nov 2013 18:28:39 +0200, Νίκος Αλεξόπουλος wrote:

> Στις 8/11/2013 6:06 μμ, ο/η Mark Lawrence έγραψε:
> 
>> But let's not waste any more time on this.  Please get back to checking
>> your web site.  She might have been hacking again.  Or little fingers
>> from one of my highly paid contractors might have been up to no good.
>> Oh but I forgot, you've made it hacker proof now.  You'll sleep much
>> better knowing your site is safe.  Or is it?
>>
>>
> 
> Many visitors per hour in my website.
> They didn't manage to mess with the db again or the variables i'm
> utilizing.
> 
> The hacker maybe a blondie and she cant get a workaround after my
> changes.
> 
> At least lest hope she is a pretty hacker wannabe :-)

let me get this straight

You have no aptitude for programming, 
your database skills are non-existent,
you have no clue regarding even basic debugging techniques,
you an an incompetent system administrator,
you cannot even follow basic instructions when you ask for assistance Yet 
you feel you can make blond jokes and belittle someone who has 
demonstrated the flaws in your set-up multiple times?

I have not laughed so much in years. You really should be on the stage, 
there is one leaving in 10 minutes.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To whoever hacked into my Database

2013-11-08 Thread unknown
On Fri, 08 Nov 2013 18:57:21 +0200, Νίκος Αλεξόπουλος wrote:

> Στις 8/11/2013 6:48 μμ, ο/η unknown έγραψε:
>> On Fri, 08 Nov 2013 18:28:39 +0200, Νίκος Αλεξόπουλος wrote:
>>
>>> Στις 8/11/2013 6:06 μμ, ο/η Mark Lawrence έγραψε:
>>>
>>>> But let's not waste any more time on this.  Please get back to
>>>> checking your web site.  She might have been hacking again.  Or
>>>> little fingers from one of my highly paid contractors might have been
>>>> up to no good. Oh but I forgot, you've made it hacker proof now. 
>>>> You'll sleep much better knowing your site is safe.  Or is it?
>>>>
>>>>
>>>>
>>> Many visitors per hour in my website.
>>> They didn't manage to mess with the db again or the variables i'm
>>> utilizing.
>>>
>>> The hacker maybe a blondie and she cant get a workaround after my
>>> changes.
>>>
>>> At least lest hope she is a pretty hacker wannabe :-)
>>
>> let me get this straight
>>
>> You have no aptitude for programming,
>> your database skills are non-existent,
>> you have no clue regarding even basic debugging techniques,
>> you an an incompetent system administrator,
>> you cannot even follow basic instructions when you ask for assistance
>> Yet you feel you can make blond jokes and belittle someone who has
>> demonstrated the flaws in your set-up multiple times?
>>
>> I have not laughed so much in years. You really should be on the stage,
>> there is one leaving in 10 minutes.
>>
>>
> 
> I have all of the above characteristics in a small degree.
> 
> If the mighty hacker is so good and i'm so bad in programming and
> securing my script why cant she break bad again?
> 
> And why are you posting under your real name but as "unknown" instead?

Because I do not want a twit like you sending me direct emails.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-10 Thread unknown
On Sat, 09 Nov 2013 15:43:53 +0200, Νίκος Αλεξόπουλος wrote:

> Στις 9/11/2013 2:45 μμ, ο/η Mark Lawrence έγραψε:
>> On 08/11/2013 23:02, Νίκος Αλεξόπουλος wrote:
>>> Στις 9/11/2013 12:49 πμ, ο/η Denis McMahon έγραψε:
 On Sat, 09 Nov 2013 00:01:37 +0200, Νίκος Αλεξόπουλος wrote:

> I saw the link and i'm wondering if it can be written in 1-liner.

 Yes, but you have to rewrite all your code in perl to do this.


>>>
>>> Please tell me and as a git i will provide you with 2 good pdfs i just
>>> found:
>>>
>>> You can see them at my website if you click the blue download button.
>>>
>>> The 1st is a Linux Bile and the 2nd is WebHosting for Dummies.
>>
>> Why is Web Security for Dummies missing?
>>
>>
> 
> It's not missing.
> Its there, check again.
> Just click on the Blue download button and select it from the list of
> buttons.

Try Reading IT!
-- 
https://mail.python.org/mailman/listinfo/python-list


replace string in a file

2008-03-15 Thread Unknown
Hi, 
I've got this code :

cb = open("testfile", "r+")
f = cb.readlines()
for line in f:
rx = re.match(r'^\s*(\d+).*', line)
if not rx:
continue
else:
serial = rx.group(1)
now = time.time()
today = time.strftime('%Y%m%d00', time.localtime(now))
todayVal, serialVal = long(today), long(serial)
if todayVal <= serialVal: 
todayVal = serialVal + 1
else: 
todayVal += 1
line = string.replace(line, serial, "%d" %todayVal)
cb.write(line + "\n")
print 'Updated serial from "%s" to "%d"' % ( serial, todayVal )
break  
cb.close()

I was expecting to replace the old value (serial) with the new one 
(todayVal). Instead, this code *adds* another line below the one found...

How can I just replace it?

Thanks for your help :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replace string in a file

2008-03-15 Thread Unknown
Thanks, andrei. I'll try that.

Le Sat, 15 Mar 2008 14:25:21 -0700, andrei.avk a écrit :

> What you want to do is either 1. load everything up into a string,
> replace
> text, close file, reopen it with 'w' flag, write string to it. OR if
> file is too big, you can read each line, replace, write to a temp file,
> then when done move the file over the old one.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: replace string in a file

2008-03-16 Thread Unknown
Le Sat, 15 Mar 2008 16:55:45 -0700, joep a écrit :

> you can also use standard module fileinput.input with ''inplace'' option
> which backs up original file automatically.
> 
> from python help for fileinput:
> 
> Optional in-place filtering: if the keyword argument inplace=1 is passed
> to input() or to the FileInput constructor, the file is moved to a
> backup file and standard output is directed to the input file (if a file
> of the same name as the backup file already exists, it will be replaced
> silently).

Thanks for the idea :)
What I do not get is how I can replace a string with that.

If I write something like:

for line in filehandle.input('myfile.txt', inplace=1):
rx = re.match(r'^\s*(\d+).*',line )
if not rx:
continue
else:
oldValue = rx.group(1)
Value = 123456789
line = string.replace(line, oldValue, "%d" Value)
print line
break 

This code replaces the whole file with line, instead of replacinf the old 
value with the new one. Did I forget something ?
-- 
http://mail.python.org/mailman/listinfo/python-list

(beginner) logging config not working

2011-04-29 Thread Unknown Moss
Hi

This is a beginner question. Thanks for the hand.

I've been asked to maintain some poorly constructed python code.
Logging is weak. Getting it to work with python logging
programmatically was easy.

However, I'd like to refactor all the logging code into configuration
since I see the need for other handlers in the future (syslog and
possibly email).

For now I just want to get console and log file working, but I'm
having problems with the log file. I'm trying some test code. Here's
my test script (logging_example.py):

import logging
import logging.config

def main():
logging.config.fileConfig("logging.conf")
logging.debug("debug check")
logging.info("info check")
logging.warn("warn check")
logging.error("err check")
logging.critical("crit check")

if __name__ == "__main__":
  main()

Here's my config (logging.conf):

[loggers]
keys=root,file

[handlers]
keys=console,file

[formatters]
keys=simple,detailed

[logger_root]
level=NOTSET
handlers=console

[logger_file]
level=DEBUG
handlers=file
qualname=mylogger

[formatter_simple]
class=logging.Formatter
format=%(asctime)s - %(name)s [%(levelname)s] - %(message)s

[formatter_detailed]
class=logging.Formatter
format=%(asctime)s - %(name)s [%(levelname)s] - %(message)s

[handler_console]
class=logging.StreamHandler
formatter=simple
args=(sys.stdout,)

[handler_file]
class=FileHandler
level=DEBUG
formatter=detailed
args=('logging_example.log', 'w')


Output:

$ python logging_example.py
2011-04-29 17:07:01,923 - root [DEBUG] - debug check
2011-04-29 17:07:01,986 - root [INFO] - info check
2011-04-29 17:07:01,986 - root [WARNING] - warn check
2011-04-29 17:07:01,986 - root [ERROR] - err check
2011-04-29 17:07:02,000 - root [CRITICAL] - crit check

The logging_example.log is created, but no entries are written to it.
Based on this configuration I'd expect all the logging entries to be
written to the file as well.

Any ideas where I'm going awry?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (beginner) logging config not working

2011-04-30 Thread Unknown Moss
On Apr 29, 10:09 pm, Peter Otten <__pete...@web.de> wrote:
> Unknown Moss wrote:
> > Hi
>
> > This is a beginner question. Thanks for the hand.
>
> > I've been asked to maintain some poorly constructed python code.
> > Logging is weak. Getting it to work with python logging
> > programmatically was easy.
>
> > However, I'd like to refactor all the logging code into configuration
> > since I see the need for other handlers in the future (syslog and
> > possibly email).
>
> > For now I just want to get console and log file working, but I'm
> > having problems with the log file. I'm trying some test code. Here's
> > my test script (logging_example.py):
>
> > import logging
> > import logging.config
>
> > def main():
> >     logging.config.fileConfig("logging.conf")
> >     logging.debug("debug check")
>
> The above is a shortcut for
>
> root = logging.getLogger("")
> root.debug("debug check")
>
> i. e. you are logging to the root logger. According to your config file
> messages sent to the root logger are only handled by the console handler:
>
> > [logger_root]
> > level=NOTSET
> > handlers=console
>
> You can either change that by adding the file handler to the list of
> handlers for the root logger
>
> handlers=console,file
>
> in the config file or by directing your logging messages to "mylogger" with
>
> mylogger = logging.getLogger("mylogger")
> mylogger.debug("debug check")
>
> Note that loggers are organized in a tree; messages sent to mylogger will be
> propagated upwords to the root logger by default.

Thanks you Peter. That worked perfectly. It points out that I'm not
really understanding the python logging concepts yet. I'll search for
more details. I need pictures.  :-)

Thanks again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (beginner) logging config not working

2011-04-30 Thread Unknown Moss
On Apr 29, 10:09 pm, Peter Otten <__pete...@web.de> wrote:
> Unknown Moss wrote:
> > Hi
>
> > This is a beginner question. Thanks for the hand.
>
> > I've been asked to maintain some poorly constructed python code.
> > Logging is weak. Getting it to work with python logging
> > programmatically was easy.
>
> > However, I'd like to refactor all the logging code into configuration
> > since I see the need for other handlers in the future (syslog and
> > possibly email).
>
> > For now I just want to get console and log file working, but I'm
> > having problems with the log file. I'm trying some test code. Here's
> > my test script (logging_example.py):
>
> > import logging
> > import logging.config
>
> > def main():
> >     logging.config.fileConfig("logging.conf")
> >     logging.debug("debug check")
>
> The above is a shortcut for
>
> root = logging.getLogger("")
> root.debug("debug check")
>
> i. e. you are logging to the root logger. According to your config file
> messages sent to the root logger are only handled by the console handler:
>
> > [logger_root]
> > level=NOTSET
> > handlers=console
>
> You can either change that by adding the file handler to the list of
> handlers for the root logger
>
> handlers=console,file
>
> in the config file or by directing your logging messages to "mylogger" with
>
> mylogger = logging.getLogger("mylogger")
> mylogger.debug("debug check")
>
> Note that loggers are organized in a tree; messages sent to mylogger will be
> propagated upwords to the root logger by default.

Thanks you Peter. That worked perfectly. It points out that I'm not
really understanding the python logging concepts yet. I'll search for
more details. I need pictures.  :-)

Thanks again.
-- 
http://mail.python.org/mailman/listinfo/python-list


(beginner question) ConfigParser nuances

2011-05-02 Thread Unknown Moss
Hi - Beginner question here. I'm working with ConfigParser. I'd like
to take a multiline variable and convert it directly to an array.
Seems like a common  problem, but I don't see how I can do it without
doing a little parsing in my own code. Here's what I'm doing ...

>>> import ConfigParser
>>> import io
>>> sample = """
... [Example]
... fruit = apple
... orange
... pear
... """
>>> config = ConfigParser.RawConfigParser()
>>> config.readfp(io.BytesIO(sample))
>>> config.get("Example", "fruit")
'apple\norange\npear'
>>> temp = config.get("Example", "fruit")
>>> temp.split()
['apple', 'orange', 'pear']

I'm thinking there's a way to avoid this intermediate temp.split()
step. Is there not a way to move a multiline value straight into an
array using ConfigParser?

Thanks for the help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (beginner question) ConfigParser nuances

2011-05-02 Thread Unknown Moss
On May 2, 3:25 pm, Chris Rebert  wrote:
> On Mon, May 2, 2011 at 3:04 PM, Unknown Moss  wrote:
> > Hi -Beginnerquestionhere. I'm working with ConfigParser. I'd like
> > to take a multiline variable and convert it directly to an array.
> > Seems like a common  problem, but I don't see how I can do it without
> > doing a little parsing in my own code. Here's what I'm doing ...
>
> >>>> import ConfigParser
> >>>> import io
> >>>> sample = """
> > ... [Example]
> > ... fruit = apple
> > ...     orange
> > ...     pear
> > ... """
> >>>> config = ConfigParser.RawConfigParser()
> >>>> config.readfp(io.BytesIO(sample))
> >>>> config.get("Example", "fruit")
> > 'apple\norange\npear'
> >>>> temp = config.get("Example", "fruit")
> >>>> temp.split()
> > ['apple', 'orange', 'pear']
>
> > I'm thinking there's a way to avoid this intermediate temp.split()
> > step. Is there not a way to move a multiline value straight into an
> > array using ConfigParser?
>
> Nope, there is not. I think some might instead use several numbered
> options to similar effect:
>
> # config file
> [Example]
> fruit1: apple
> fruit2: orange
> fruit3: pear
>
> # Python
> from itertools import count
> fruits = []
> names = ("fruit" + str(i) for i in count(1))
> for name in names:
>     if not config.has_option("Example", name):
>         break
>     fruits.append(config.get("Example", name))
>
> Cheers,
> Chris
> --http://rebertia.com

Ok, thanks Chris. Maybe I'm getting too lazy in my old age.  :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Is Python appropriate for web applications?

2005-04-14 Thread Unknown User
I am a Python programmer and I'm thinking about learning PHP, which is  
similar to C++ (quite
different from Python). I want to start writing web applications. Do you  
think if I learn
PHP I'll develop faster? Does PHP have more features? How about the speed  
of execution? What
are the pros and cons? Our server can run both Python, Perl and PHP, so I  
have the choice.
Thanks for your opinion,

--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python appropriate for web applications?

2005-04-16 Thread Unknown User
Thank you very much.
On Fri, 15 Apr 2005 06:47:14 -0300, Peter Maas <[EMAIL PROTECTED]> wrote:
Unknown User schrieb:
I am a Python programmer and I'm thinking about learning PHP, which is
similar to C++
wrong
(quite  different from Python).
true
I want to start writing web applications. Do  you  think if I learn
 > PHP I'll develop faster?
Nobody but you can anawer this question. You'll have to try.
Does PHP have more features?
PHP has a rich library which probably outperforms any Python alternative
in terms of features. But this doesn't necessarily mean that you will
develop faster in PHP. The problem with Python is that you have to make
a choice among many solutions (roughly ordered by inreasing complexity):
- plain cgi
- Quixote
- modpython
- CherryPy
- Spice
- Webware
- Twisted
- ZOPE
...
Have a look at http://www.python.org/topics/web/
How about the speed  of execution?
There is no simple answer. Both languages use C functions which are
executed at CPU speed. But with interpreted code Python seems to be
approximately 3-4 times faster than PHP (http://dada.perl.it/shootout/).
What are the pros and cons?
http://www.allsites.com/Top.Computers.Programming.Languages.Comparison_and_Review.html

--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
--
http://mail.python.org/mailman/listinfo/python-list


Scanning through Windows registry...

2008-05-06 Thread Unknown Hero
Hi everyone!

Well, I have this need for a Python script that will scan through a
selected hive (like HKEY_LOCAL_MACHINE) and replace all strings that
contain word xxx (IE. foo) with yyy (IE. moo). I do not want partial
results, but rather complete strings (no foome or the like, just foo).


I have a basic understanding of Python, but this is beyond my skills.

I was looking for something like this:

open key (HKEY_LOCAL_MACHINE)
while (not end of list)
  open next subkey
  search subkey for value (old)
  SetValue(key, subkey, REG_SZ, new)
  close subkey
end while
close key
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-06 Thread Unknown Hero
Tim Golden wrote:
> In a spirit of teaching people to fish...
>
> ... If you put something like "Python windows registry" into Google, you
> get quite a few hits, the top one of which is probably pointing to the stdlib
> _winreg module, but several others point towards wrapper classes, modules
> etc. which provide a simpler or at least a different interface to the 
> registry.
>
> Have a look at those and see if you can't work out what to do.
>
> TJG

The first link which points to the Python documentation for the
_winreg module I already checked, even before coming here. I am
wondering how I should do the loop I need (go through
HKEY_LOCAL_MACHINE and read one subkey at a time, if it contains this
'foo' then change it into 'moo'). As I already said, I am by no means
an expert in Python (heck, I learned the basics only a month ago).
However, I am willing to learn.

Also my prior experience with the Windows registry is mostly by the
Registry Editor shipped with Windows. While I do understand what keys,
values and hives are, I do not have a great experience in the others.

If it's not too much to ask, maybe someone (who is much better than
me) could make a code snippet that reads a certain hive and replaces
values that are predetermined (preferably variables, not arguments if
possible).

If that's out of the question, at least push me gently into the right
direction.

So basically I am looking for these things:

1) Read one subkey from HKEY_LOCAL_MACHINE at a time (I think
QueryValueEx() is needed here)
2) Check if said subkey contains some predetermined string (like 'foo'
here)
3) If the above applies, change the value into another predetermined
string (like 'moo' here)


Also, how should I determine the length of the loop? I personally am
too fond of the for loop, but if I need to use, like, while, then so
be it.

Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-06 Thread Unknown Hero
Tim Golden wrote:

> Well, I attach a kind of explanatory Noddy example I wrote a few years ago
> for someone on the python-win32 list. I think, glancing over it, that it 
> includes
> what you need to know, although not necessarily in the right order. I'm happy 
> to
> explain if things aren't clear:
>
> 
> import _winreg
>
> HKLM = _winreg.HKEY_LOCAL_MACHINE
>
> #
> # Set up a registry subtree under HKLM\Software
> # which will look like this:
> #
>
> #
> # TimSoft
> # |
> # +-- App1
> # |
> # +-- App2
> # |
> # +-- App3
> #
>
> #
> # The [TimSoft] key has a default (ie unnamed) value
> # while the Appx keys each have two values:
> #   [Registered] - a string Y/N value
> #   [Version] - a DWORD value
> #
>
> hSoftware = _winreg.OpenKey (HKLM, "Software")
> hTimSoft = _winreg.CreateKey (hSoftware, "TimSoft")
>
> _winreg.SetValueEx (hTimSoft, None, 0, _winreg.REG_SZ, "All Tim's Software")
>
> hApp1 = _winreg.CreateKey (hTimSoft, "App1")
> _winreg.SetValueEx (hApp1, "Version", 0, _winreg.REG_DWORD, 101)
> _winreg.SetValueEx (hApp1, "Registered", 0, _winreg.REG_SZ, "Y")
>
> hApp2 = _winreg.CreateKey (hTimSoft, "App2")
> _winreg.SetValueEx (hApp2, "Version", 0, _winreg.REG_DWORD, 202)
> _winreg.SetValueEx (hApp2, "Registered", 0, _winreg.REG_SZ, "N")
>
> hApp3 = _winreg.CreateKey (hTimSoft, "App3")
> _winreg.SetValueEx (hApp3, "Version", 0, _winreg.REG_DWORD, 303)
> _winreg.SetValueEx (hApp3, "Registered", 0, _winreg.REG_SZ, "Y")
>
> #
> # NB - no need to do an explicit "write": the Registry uses
> #  some sort of caching which eventually catches up with itself,
> #  so unless you plan to turn the machine off soon, don't
> #  bother with FlushKey or anything like that.
> #
>
> #
> # Now we start again, as though we were just querying
> #
>
> hTimSoft = _winreg.OpenKey (HKLM, r"Software\TimSoft")
> n_sub_keys, n_values, last_modified = _winreg.QueryInfoKey (hTimSoft)
> print n_sub_keys, "sub keys", n_values, "values", last_modified, "nanoseconds 
> since 1600!"
>
> #
> # Pick up the default value: really should try to
> #  interpret the default_type to determine if it's
> #  a number or a string or whatever, but...
> #
> default_value, default_type = _winreg.QueryValueEx (hTimSoft, None)
> print "Default value:", default_value
>
> #
> # Now, in this case I know (because I created them) that
> #  the TimSoft key has three subkeys, each of which has
> #  two values. But if I didn't...
> #
> print
> for i in range (n_sub_keys):
>   subkey_name = _winreg.EnumKey (hTimSoft, i)
>   print subkey_name
>
> #
> # Alternatively, if I hadn't done the QueryInfoKey above...
> #
> i = 0
> print
> while 1:
>   try:
>     subkey_name = _winreg.EnumKey (hTimSoft, i)
>   except EnvironmentError:
>     break
>   else:
>     print subkey_name
>     i += 1
>
> #
> # Now, let's use the last key as an example
> #  and pick out its values.
> #
> print
> print subkey_name
> hAppKey = _winreg.OpenKey (hTimSoft, subkey_name)
> i = 0
> while 1:
>   try:
>     name, value, type = _winreg.EnumValue (hAppKey, i)
>     print name, value, type
>   except EnvironmentError:
>     break
>   else:
>     print "  %s => %s (type %s)" % (name, value, type)
>     i += 1
>
> 
>
> TJG

Correct me if I'm wrong (which I just might be), but doesn't the above
code go through the keys behind HKEY_LOCAL_MACHINE\Software\Timsoft\ ?

Is it possible to use an empty value in:

  hTimSoft = _winreg.OpenKey (HKLM, r"Software\TimSoft")

like:

  hTimSoft = _winreg.OpenKey (HKLM, "")

so it would go all subkeys behind the "root" (in this case,
HKEY_LOCAL_MACHINE)?


The code is supposed to work even if I don't know all possible subkeys
under HKEY_LOCAL_MACHINE. Creating dozens or hundreds of handles like
the above is a bit... unappealing.

Can I also use HKLM in the place of hTimSoft when I want to determine
the amount of subkeys it has, like you did over here:

  n_sub_keys, n_values, last_modified = _winreg.QueryInfoKey
(hTimSoft)


Anyway, the above code seems interesting. I'll try a few tweaks here
and there and see what happens.

Thank you, Tim.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-07 Thread Unknown Hero
Thank you, I think I can manage now. It's nice that you could spare
some time to help me in this, Tim. People like you make the world a
better place :)

I'll post my code here once I have time to write it, currently I'm
rather busy. That is merely for optimization suggestions and for
others who might need the same sort of code I did.


Thank you once again.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-09 Thread Unknown Hero
On 7 touko, 14:25, Unknown Hero <[EMAIL PROTECTED]> wrote:
> I'll post my code here once I have time to write it, currently I'm
> rather busy. That is merely for optimization suggestions and for
> others who might need the same sort of code I did.
>
> Thank you once again.

Finally managed to get it to work (heh, I was pretty darn lost even
though I had the best help) but as promised, I'll post my code here
for those who might be interested in it. The biggest of thanks to Tim
Golden, who basically walked me step-by-step through this. Most of the
code is copied from his examples above.


#Goes through all keys and subkeys in the selected hive (defined as
root) and replaces the value 'old' with the value 'new'
#
#IMPORTANT! You should always back up the registry before attempting
to modify it.
#The author of this script CANNOT BE HELD RESPONSIVE for any damage
caused by running this script.
#
#To customize the script to your liking, you can alter the values old,
new, root.
#
#old and new can be any string value
#root has to be one of the following:
#
# _winreg.HKEY_LOCAL_MACHINE
# _winreg.HKEY_CURRENT_USER
# _winreg.HKEY_CLASSES_ROOT
# _winreg.HKEY_USERS
# _winreg.HKEY_CURRENT_CONFIG

import _winreg

HIVES = {
  "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE,
  "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER,
  "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT,
  "HKEY_USERS" : _winreg.HKEY_USERS,
  "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG

}

old = "This was value before"
new = "This is new value"

start = "HKEY_LOCAL_MACHINE\\"
startHandle = _winreg.HKEY_LOCAL_MACHINE

#Values for start and startHandle are: HKEY_LOCAL_MACHINE,
HKEY_CURRENT_USER, HKEY_CLASSES_ROOT, HKEY_USERS, HKEY_CURRENT_CONFIG


class RegKey:

  def __init__ (self, name, key):
 self.name = name
 self.key = key

  def __str__ (self):
return self.name

def walk (top):
  """walk the registry starting from the key represented by
  top in the form HIVE\\key\\subkey\\..\\subkey and generating
  key, subkey_names, values at each level.

  key is a lightly wrapped registry key, including the name
  and the HKEY object.
  subkey_names are simply names of the subkeys of that key
  values are 3-tuples containing (name, data, data-type).
  See the documentation for _winreg.EnumValue for more details.
  """
  try:
if "\\" not in top: top += "\\"
root, subkey = top.split ("\\", 1)
#print "KEY:", root + "\\" + subkey
key = _winreg.OpenKey (HIVES[root], subkey, 0, _winreg.KEY_READ |
_winreg.KEY_SET_VALUE)
subkeys = []
i = 0
while True:
  try:
subkeys.append (_winreg.EnumKey (key, i))
i += 1
  except EnvironmentError:
break

values = []
i = 0
while True:
  try:
values.append (_winreg.EnumValue (key, i))
i += 1
  except EnvironmentError:
break

yield RegKey (top, key), subkeys, values

for subkey in subkeys:
  for result in walk (top + "\\" + subkey):
yield result

  except WindowsError:
#print 'Could not open key', root + "\\" + subkey + "\n"
pass

basickeys = []
i = 0
while True:
  try:
basickeys.append (_winreg.EnumKey (startHandle, i))
i += 1
  except EnvironmentError:
print i, 'subkeys found!'
break

for x in range(len(basickeys)):
  for key, subkey_names, values in walk (start + basickeys[x]):
#print key
for (name, data, type) in values:
#  print "  ", name, "=>", data
  if type == _winreg.REG_SZ and old in data:
_winreg.SetValueEx (key.key, name, 0, type, data.replace (old,
new))



Not the most effecient code, I'm sure, but it does what I want it to
do :D

Thank you once more, Tim. Also, thank you, Mike, for your advice on
saving the registry. I would have forgotten to note backing up the
registry in the beginning if it wasn't for you bringing that up. :D
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-09 Thread Unknown Hero
On 9 touko, 12:51, Unknown Hero <[EMAIL PROTECTED]> wrote:

> Finally managed to get it to work (heh, I was pretty darn lost even
> though I had the best help) but as promised, I'll post my code here
> for those who might be interested in it. The biggest of thanks to Tim
> Golden, who basically walked me step-by-step through this. Most of the
> code is copied from his examples above.
>
> [large piece of code here]
>
> Not the most effecient code, I'm sure, but it does what I want it to
> do :D
>
> Thank you once more, Tim. Also, thank you, Mike, for your advice on
> saving the registry. I would have forgotten to note backing up the
> registry in the beginning if it wasn't for you bringing that up. :D

Hmm... Improving your code is always fun :D but quick fixes to make it
replace search results that contain something more than 'old' here
don't
seem to work.

So I made it command-line, with arguments Hive, old, new.

If I ran the script as registry.py HKEY_LOCAL_MACHINE something
"something else"
and I had made dummy values to the registry like "there is something
here" it
won't update to "there is something else here".

I tried this, can Tim (or someone else) possibly help?

if type == _winreg.REG_SZ:
  Character = 0
  Correct = 0
  FoundStart = FoundEnd = 0
  Found = False
  for y in range(len(data)):
if Character < len(old):
  if old[Character] is data[y]:
Character = Character + 1
Correct = Correct + 1
  if Correct is len(old):
Found = True
Replace = ""
Character = 0
for y in range(len(data)):
  if old[0] is data[y]:
FoundStart = int(y)
FoundEnd = FoundStart + oldLength
for y in range(FoundStart):
  Replace = Replace + data[y]

for y in range(len(new)):
  Replace = Replace + new[y]

for y in range(FoundEnd, len(data)):
  Replace = Replace + data[y]

  if Found:
_winreg.SetValueEx (key.key, name, 0, type, data.replace
(old, Replace))


Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-09 Thread Unknown Hero
Ah, never mind, got it to work. Here's the code now. I hope I won't
run into another problems later :D



#Goes through all keys and subkeys in the selected hive (defined as
root) and replaces the value 'old' with the value 'new'
#
#IMPORTANT! You should always back up the registry before attempting
to modify it.
#The author of this script CANNOT BE HELD RESPONSIVE for any damage
caused by running this script.
#
#To customize the script to your liking, you can alter the values old,
new, root.
#
#old and new can be any string value
#root has to be one of the following:
#
# _winreg.HKEY_LOCAL_MACHINE
# _winreg.HKEY_CURRENT_USER
# _winreg.HKEY_CLASSES_ROOT
# _winreg.HKEY_USERS
# _winreg.HKEY_CURRENT_CONFIG

import _winreg #For accessing windows registry, included in Python
2.0.
import sys #For reading arguments (command line), included in every
Python release.

HIVES = {
  "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE,
  "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER,
  "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT,
  "HKEY_USERS" : _winreg.HKEY_USERS,
  "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG
}


class RegKey:

  def __init__ (self, name, key):
 self.name = name
 self.key = key

  def __str__ (self):
return self.name

def walk (top):
  """walk the registry starting from the key represented by
  top in the form HIVE\\key\\subkey\\..\\subkey and generating
  key, subkey_names, values at each level.

  key is a lightly wrapped registry key, including the name
  and the HKEY object.
  subkey_names are simply names of the subkeys of that key
  values are 3-tuples containing (name, data, data-type).
  See the documentation for _winreg.EnumValue for more details.
  """
  try:
if "\\" not in top: top += "\\"
root, subkey = top.split ("\\", 1)
#print "KEY:", root + "\\" + subkey
key = _winreg.OpenKey (HIVES[root], subkey, 0, _winreg.KEY_READ |
_winreg.KEY_SET_VALUE)
subkeys = []
i = 0
while True:
  try:
subkeys.append (_winreg.EnumKey (key, i))
i += 1
  except EnvironmentError:
break

values = []
i = 0
while True:
  try:
values.append (_winreg.EnumValue (key, i))
i += 1
  except EnvironmentError:
break

yield RegKey (top, key), subkeys, values

for subkey in subkeys:
  for result in walk (top + "\\" + subkey):
yield result

  except WindowsError:
#print 'Could not open key', root + "\\" + subkey + ", access
denied!\n"
pass

  except:
print 'Other error!'


def main(start, startHandle, old, new):
  basickeys = []
  i = 0
  while True:
try:
  basickeys.append (_winreg.EnumKey (startHandle, i))
  i += 1
except EnvironmentError:
#  print i, 'subkeys found!'
  break

  for x in range(len(basickeys)):
for key, subkey_names, values in walk (start + "\\" +
basickeys[x]):
#  print key
  for (name, data, type) in values:
#print "  ", name, "=>", data
if type == _winreg.REG_SZ:
  Character = 0
  Correct = 0
  FoundStart = FoundEnd = 0
  Found = False
  for y in range(len(data)):
try:
  if Character < len(old):
 #   print old[Character], data[y]
if old[Character] in data[y]:
  Character = Character + 1
  Correct = Correct + 1
except:
  pass
  if Correct is len(old):
#print 'Debug!'
Replace = ""
Character = 0
for y in range(len(data)):
  if not Found:
if old[0] in data[y]:
  FoundStart = int(y)
  FoundEnd = FoundStart + len(old)
  Found = True
#for y in range(FoundStart):
#  Replace = Replace + data[y]

for y in range(len(new)):
  Replace = Replace + new[y]

#for y in range(FoundEnd, len(data)):
#  Replace = Replace + data[y]
Found = True
  if Found:
#print "OLD:", old, "will be replaced with:", Replace
_winreg.SetValueEx (key.key, name, 0, type, data.replace
(old, Replace))


def help():
  #Show help
  print 'USAGE: Registry.py [HIVE] [OLD] [NEW]'
  print '  HIVE: The root key in registry you want to go through.'
  print 'HKEY_CLASSES_ROOT'
  print 'HKEY_CURRENT_USER'
  print 'HKEY_LOCAL_MACHINE'
  print 'HKEY_USERS'
  print 'HKEY_CURRENT_CONFIG'
  print ''
  print '  OLD:  The value to search for.'
  print 'Wrap multiword strings with \"\".'
  print ''
  print '  NEW:  The value which will replace OLD.'
  print 'Wrap multiword strings with \"\".'

#Check for arguments
#HIVE, old, new

while True:
  #Check if invalid number of arguments are given
  if len(sys.argv) is 1:
help()
break

#  for x in range(len(sys.argv)):
#print 'sys.argv[' + str(x) + ']:', sys.argv[x]

  #Check if hive is