Re: [Tutor] help with script

2011-12-28 Thread Alan Gauld

On 28/12/11 01:31, nickto...@comcast.net wrote:

hello, my name is nick. i got python for software design by Allen B.
Downey as a gift for christmas. i am completely new to programming


Welcome, we are here to help :-)


5
x=5
x+1
im ok when it comes to using python so far. but it has asked me to put
the problem into a script and run it. my question is how do i put that
problem into a script and then how do i run it in python.


The Python interpreter interactiove prompt (>>>) does a neat trick of 
evaluating expressions and printing the result. So the 3 expressions you 
have will evaluate to 2 values:


5
6
The x assignment will not print any result.

When you put things in a script (just a text file containing python 
commands)  and run it, the interpreter will not display the result of an 
expression, you have to tell it explicitly to do that, using print().


So to make your three lines of code into a script open up any
text editor (Notepad will do for this one but you will probably
find IDLE is better longer term)

Into that file type

print (5)
x = 5
print (x+1)


Now save the file. Give it any name you like but with a .py extension.
Lets say you choose test1.py. Now if you double click that file in 
Windows explorer (I'm assuming you are on Windows, if MacOS or Linux 
suibstitute your own favourite File manager) the program will start up 
run and close down so quickly you won;t be able to read it.


To get round that add a final line:

input("Hit Enter to quit...")

Don't worry what it does just yet, just make sure its the last line in 
the file. Now, when you start the test1.py it will pause before closing 
until you hit enter.


Try that and let us know if you hit any problems.

You might also like to browse the folowing topics in my tutorial,
they all gradually introduce the idea of running Python scripts:
- Getting Started
- More Sequences
- Add a little Style


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python logger

2011-12-28 Thread Timo

Op 28-12-11 18:13, rail shafigulin schreef:
has anyone used python logger before? i'm trying to adapt it for my 
workplace. right now it is pretty simplistic for me. i'm trying to 
generate extra output by the LoggerAdapter.  however i'm getting 
errors. specifically i get the following message:


Traceback (most recent call last):
  File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit
msg = self.format(record)
  File "/usr/lib/python3.1/logging/__init__.py", line 650, in format
return fmt.format(record)
  File "/usr/lib/python3.1/logging/__init__.py", line 438, in format
record.message = record.getMessage()
  File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting
Without reading the code, you are passing too many arguments for a 
format string.


>>> msg = 'one arg %s and a second %s'
>>> msg % ('foo', 'bar', 'baz') # Pass 3 arguments
Traceback (most recent call last):
  File "", line 1, in 
TypeError: not all arguments converted during string formatting

Cheers,
Timo



i'm using this 
 
documentation. any


here is my code

import logging
import logging.handlers

class TestInfo(object):
  def __init__(self, test_name = None,
   description = '',
   notes = '',
   expected = None,
   actual = None,
   status = 'Fail',
   timestamp = None):
self.__test_name = test_name
self.__description = description
self.__notes = notes
self.__expected = expected
self.__actual = actual
self.__status = status
self.__timestamp = timestamp

  def __getitem__(self, name):
"""
To allow this instance to look like a dict.
"""
result = None
if 'test_name' == name:
  result = self.__test_name
elif 'description' == name:
  result = self.__description
elif 'notes' == name:
  result = self.__notes
elif 'expected' == name:
  result = self.__expected
elif 'actual' == name:
  result = self.__actual
elif 'status' == name:
  status = self.__status
elif 'timestamp' == name:
  timestamp = self.__timestamp
else:
  result = self.__dict__.get(name, "?")
return result

  def __iter__(self):
"""
To allow iteration over keys, which will be merged into
the LogRecord dict before formatting and output.
"""
names = ['test_name', 'description', 'notes', 'expected', 
'actual', 'status', 'timestamp']

names.extend(self.__dict__.keys())
return names.__iter__()

def main():
  testinfo = TestInfo(
test_name = 'myname',
description = 'mydescription',
notes = 'mynotes',
expected = 'myexpected',
actual = 'myactual',
status = 'Fail',
timestamp = 'mystamp')

  mylogger = logging.getLogger('mylogger')
  mylogger.setLevel(logging.DEBUG)

  filehandler = logging.FileHandler('test.log')
  filehandler.setLevel(logging.DEBUG)

  mylogger.addHandler(filehandler)
  mylogadapter = logger.LoggerAdapter(mylogger, testinfo)
mylogadapter.info ('this is a log message', 
testinfo)


if __name__ == "__main__":
  main()

any help on how to add extra output parameters is appreciated.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python logger

2011-12-28 Thread Peter Otten
rail shafigulin wrote:

> has anyone used python logger before? i'm trying to adapt it for my
> workplace. right now it is pretty simplistic for me. i'm trying to
> generate
> extra output by the LoggerAdapter.  however i'm getting errors.
> specifically i get the following message:
> 
> Traceback (most recent call last):
>   File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit
> msg = self.format(record)
>   File "/usr/lib/python3.1/logging/__init__.py", line 650, in format
> return fmt.format(record)
>   File "/usr/lib/python3.1/logging/__init__.py", line 438, in format
> record.message = record.getMessage()
>   File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage
> msg = msg % self.args
> TypeError: not all arguments converted during string formatting
> 
> i'm using
> thisdocumentation.
> any
> 
> here is my code

[snip]

That's not the actual code; it fails with another exception:

Traceback (most recent call last):
  File "logger_orig.py", line 74, in 
main()
  File "logger_orig.py", line 70, in main
mylogadapter = logger.LoggerAdapter(mylogger, testinfo)
NameError: global name 'logger' is not defined

In the actual code the line

>   mylogadapter = logger.LoggerAdapter(mylogger, testinfo)

has probably logging instead of logger. Under that assumption:

Technically you get an error because you have a format string without any 
placeholders. When the info() method of a Logger (or LoggerAdapter) receives 
more than one argument it tries to use the first argument as a format string 
as demonstrated below:

>>> import logging
>>> logging.basicConfig(level=logging.INFO)
>>> logging.info("foo")
INFO:root:foo
>>> logging.info("foo", "bar")
Traceback (most recent call last):
  File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit
msg = self.format(record)
  File "/usr/lib/python3.1/logging/__init__.py", line 650, in format
return fmt.format(record)
  File "/usr/lib/python3.1/logging/__init__.py", line 438, in format
record.message = record.getMessage()
  File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting
>>> logging.info("foo BAR:%s", "bar")
INFO:root:foo BAR:bar
>>> logging.info("foo BAR:%s BAZ:%s", "bar", "baz")
INFO:root:foo BAR:bar BAZ:baz

I've not used a LoggerAdapter myself, but as I read the docs it is meant to 
simplify the addition of extra data, e. g. if you have

common_extra = {"notes": "whatever"}
...
logger.info("one", extra_common_extra)
...
logger.info("two", extra=common_extra)
...
logger.info("three", extra=common_extra)
...

you can simplify that to

logger = logging.LoggingAdapter(logger, {"notes": "whatever"})
...
logger.info("one")
...
logger.info("two")
...
logger.info("three")

Applying the principle to your code:

def main():
# recommended indent is 4 spaces
testinfo = TestInfo(
test_name='myname',
description='mydescription',
notes='mynotes',
expected='myexpected',
actual='myactual',
status='Fail',
timestamp='mystamp')

mylogger = logging.getLogger('mylogger')
mylogger.setLevel(logging.DEBUG)

filehandler = logging.FileHandler('test.log')
filehandler.setLevel(logging.DEBUG)

# added to verify that testinfo is indeed passed on:
formatter = logging.Formatter(logging.BASIC_FORMAT + " notes: 
%(notes)s")
filehandler.setFormatter(formatter)

mylogger.addHandler(filehandler)
mylogadapter = logging.LoggerAdapter(mylogger, testinfo)
mylogadapter.info('this is a log message')
#without adapter the above line would be:
#mylogger.info('this is a log message', extra=testinfo)

if __name__ == "__main__":
main()


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python logger

2011-12-28 Thread Lie Ryan

On 12/29/2011 04:13 AM, rail shafigulin wrote:

has anyone used python logger before? i'm trying to adapt it for my
workplace. right now it is pretty simplistic for me. i'm trying to
generate extra output by the LoggerAdapter.  however i'm getting errors.
specifically i get the following message:

Traceback (most recent call last):
   File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit
 msg = self.format(record)
   File "/usr/lib/python3.1/logging/__init__.py", line 650, in format
 return fmt.format(record)
   File "/usr/lib/python3.1/logging/__init__.py", line 438, in format
 record.message = record.getMessage()
   File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage
 msg = msg % self.args
TypeError: not all arguments converted during string formatting


Please don't trim the traceback, your traceback is missing the top-most 
trace which will be the most useful in identifying your current problem.


Your problem is here:

mylogadapter.info('this is a log message', testinfo)

The first argument of the logging function is used as a format string 
for the following arguments. Since you're passing testinfo as a second 
argument to .info(), you need a placeholder in your first argument, e.g.:


mylogadapter.info('this is a log message, testinfo: %s', testinfo)

the logger will convert testinfo into a string and substitute that to %s 
in the format string.


Also, for your TestInfo class, you may want to look into 
collections.namedtuple.



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor