jlm699 320 Veteran Poster

Ive got that one too... what should i do next?

Open the archive, extract the files to your site-packages directory and use them as needed.

jlm699 320 Veteran Poster

Ive been searching on google but I cant find an .exe or a .zip file, for example Pmw.exe or Pmw.zip.
But I could find loads of tar.gz files, does this means that I cant have it, of course winzip cant open a file that is made for unix systems.
What can i do?

Do yourself a favor and uninstall winzip. Download 7zip, which can handle all the important compressed formats

jlm699 320 Veteran Poster

I guess I will have to do the .0 'trick'. Maybe some other folk will know a way.

Thanks wildgoose for your help.

You could do this:

float(4)/5

Or if you wanted to perform the from __future__ import division and still get integer returns you could simply turn the answer into an int like this:

>>> ans = 5 / 2
>>> ans
2.5
>>> int(ans)
2
>>>
jlm699 320 Veteran Poster

(a & b):
What happens with logical and? If a is false, does python evaluates b or not?

No. Here's the code I just used to check this:

>>> def a():
...     print 'a'
...     return False
...     
>>> def b():
...     print 'b'
...     return True
...     
>>> a() and b()
a
False
>>> b() and a()
b
a
False
>>>
vegaseat commented: good example +13
jlm699 320 Veteran Poster

Simply use the repr command:

>>> print(repr(s))
"'Quote Example'\tby person\n"
>>> print(s)
'Quote Example'	by person

>>>
jlm699 320 Veteran Poster

Hi. Thanks a lot for your response. You gave me the tip I was looking for. os.getcwd() did the trick.

file_path = os.getcwd() + "\\some_file.xls"
exc.open(file_path)

Cheers.

As a tip: You don't need to use the + "\\ ... as you could use os.path.join(os.getcwd(), 'some_file.xls') . Although it's your preference... Just this way you don't need to worry about the escape/path characters.

jlm699 320 Veteran Poster

I use multiprocessing/pyprocessing, not threading

woooee: I've seen you mention this before. What makes you choose multi-process over multi-threads? I don't use either, so I'm just wondering if you see a particular advantage in one over the other.

jlm699 320 Veteran Poster

There are two ways I know to do this:
1) Use an absolute path, ie instead of simply some_file.xls specify "C:/Documents and Settings/UserName/My Documents/some_file.xls" 2) Change the current working directory using os.chdir(desired_path) . You can also check your current working directory using os.get_cwd()

jlm699 320 Veteran Poster

Please read this explanation of property.getter, setter and deleter decorators. It should help you figure out some of the problems with your code.

jlm699 320 Veteran Poster
>>> import prueba 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "prueba.py", line 5, in <module>
    class Rect(object):
  File "prueba.py", line 33, in Rect
    @_setWidth.setter
NameError: name '_setWidth' is not defined

My question is, what is the meaning of this error? Because I don't know what I should change in order to run the program.I think that the error must be in the property.

The meaning is that _setWidth is not defined when you tried to access it. By attempting to decorate _setWidth with _setWidth.setter (what version of Python are you using?), you've asked Python to access _setWidth before you've defined it! That is why the NameError occurs.

jlm699 320 Veteran Poster

In order to better help you, you'll need to help us (the other forum members). Clearly presenting your problem will allow us to quickly scan your post and answer your question.

In order to achieve this, you must use code tags when posting any code/traceback in this forum. By doing this, we get a clear distinction as to which part of your post is a message, and which part is code. I will demonstrate the code tags with an example of a NameError, so that hopefully you understand what it means:

>>> print(foo)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'foo' is not defined
>>> foo = 'bar'
>>> print(foo)
bar
>>> 

As you can see, I hadn't yet defined foo. After doing so, the error disappeared. So in your case, you'll need to make sure that the object you're trying to access is available to the current scope of the program.

jlm699 320 Veteran Poster

but how do I pass the dictionary to the module. is there a specific command to use.

I don't see your specific call to the thermodynamics.Entropy() function, but here are the basics for passing a variable to a function:

# First we define a function, you'll notice it has two parameters, var1 and var2
>>> def my_function(var1, var2):
...     print 'This is the first var:', var1
...     print 'This is the 2nd var:', var2
...     
# Now I'll create two arbitrary objects, a and d
>>> a = 5
>>> d = { 'a':1, 'b':2, 'c':3 }
# To pass these two objects to my_function, I place them in the parenthesis when calling it
>>> my_function(a,d)
This is the first var: 5
This is the 2nd var: {'a': 1, 'c': 3, 'b': 2}
# Now I'll redefine the function to specifically access an element in the dictionary that I passed
>>> def my_function(var1, var2):
...     print 'This is the first var:', var1
...     print 'This is the a element in var2:', var2['a']
...     
>>> my_function(a,d)
This is the first var: 5
This is the a element in var2: 1
>>>

So that's the basics. Now for your specific case, you'll either need to modify the definition of Entropy to specifically expect a dictionary for you to access, or you'll need to roll that dictionary into the parameters object that you pass to this function.

It all depends on your preference

jlm699 320 Veteran Poster
import thermodynamics
oxygen={'A':31.32234, 'B':-20.23531, 'C':57.86644, 'D':-36.50624, 'E':-0.007374, 'F':-8.903471, 'G':246.7945, 'H':0.000000,'EnthalpyTempZero':8.68, 'frequency':1580.19, 'EDFT':-4.9316435}
Oshomate= oxygen['A'], oxygen['B'], oxygen['C'],oxygen['D'], oxygen['E'],oxygen['F'],oxygen['G'],oxygen['H']
print EntropyO
EnthalpyEntropyO = thermodynamics.EnthalpyEntropy(EnthalpyO,oxygen['EnthalpyTempZero'], EntropyO, temperature)

When I run the scripts, it gives an error message "NameError: global name 'A' is not defined". How can I get the module to access the dictionary values in the running script?

You'll need to pass the dictionary to your Entropy function in the module thermodynamics . Then within the function you simply do as you've done in the "running script":

oxygen['A']

This returns the value of the element with the key 'A' in the dictionary oxygen

jlm699 320 Veteran Poster

(The reason I have two "setup" methods is because in the first one I return a variable, and in the second one I have to bind an action to a key. As far as I know, these can't both be done within the same method.)

That is misinformation, what led you to believe that?

jlm699 320 Veteran Poster

Hi all,

I'm trying to mimic an html form that calls a script on the web. When I put the form together on a page, it works, and I was wondering if there was a way I could "scrape" this post request and see what I'm missing when I try to do it with Python?

If you've got Firefox you can load up Firebug and take a look at the POST contents under the Net panel. This is also a nice way to see what Headers are sent to authenticate with websites, which you can then spoof with your Python code.

jlm699 320 Veteran Poster

This is the error:

Traceback (most recent call last):
  File "C:\Python26\hotmailSender.py", line 11, in <module>
    s.login(user, password)
  File "C:\Python26\lib\smtplib.py", line 552, in login
    raise SMTPException("SMTP AUTH extension not supported by server.")
SMTPException: SMTP AUTH extension not supported by server.

Any ideas? Thanks Dan08.

The server you're attempting to connect to must not be hotmail's SMTP server. It's possible that you're connecting to the wrong port. Or the wrong server in general.

jlm699 320 Veteran Poster

I'm not sure what programming questions the dietel book poses, but when I learned Python I found the exercises included in "Dive into Python" immeasurable with how much they helped me.

This book is geared more towards those with prior programming experience. They assume you understand the concepts of variables, conditional statements, looping, etc.

jlm699 320 Veteran Poster

Thanks for reply

If i set the second index as END, then it will receive string data
from line#(index1) to the END..
but I need to read string line by line, not directly from certain line to the end.

If there is no method or attribute for this,
seems like string.split is the only option..

Did you follow that link I posted? There are special ways to work with indices such as "line.end", lineend, etc... Try reading up on that page that is linked and see if those don't answer your question.

jlm699 320 Veteran Poster

I believe you can specify the second index as END... refer to the text widget indices guide here.

These mostly seem to be tk constants, but let me know if that is a misconception.

jlm699 320 Veteran Poster

@jlm699: 2.2^2 = 4.84 (and not 4.840000000001, try it with a calculator or the google link you gave)

Yes, but that .000000000001 is obviously due to binary floating-point arithmetic.

>>> '%f' % 2.2**2
'4.840000'
>>> '%.2f' % 2.2**2
'4.84'
>>>
jlm699 320 Veteran Poster

Because if I just replace T = Test() with T = Test(myapp), the argument it pass to "__init__", not "run". How would I go about doing this?

There might be a smarter way of doing this, but you could store those variables in a member at the __init__ function and then access those members as needed in run.

jlm699 320 Veteran Poster

2.2**2 resulting 4.840000000000001

which we all know that is incorrect.

Why is that incorrect? http://www.google.com/search?q=2.2^2

jlm699 320 Veteran Poster

Now what i wish to do is read a file, use a dictionary to search lines, and then get these lines and write to a new out put file. Is that possible?

That is how I interpret your question, so let me know if I read it wrong.

To read and/or write to a file you use the builtin open method, here's the documentation.

I'm not sure what you mean by use a dictionary to search lines.

jlm699 320 Veteran Poster

That's because you're printing inputstr again... The re.sub method isn't an "in-place" transformation. You actually need to save the output like so:

import os
import re

inputstr = "HI\n//asgwrg\nasdg"
print(inputstr)

outputstr = re.sub("\/\/(.*)(\n)*", "|REP|\n", inputstr)
print("\nNEW:\n",outputstr)

Here's my output:

HI
//asgwrg
asdg

NEW:
HI
|REP|
asdg
jlm699 320 Veteran Poster

What if I would like to change the file's privileges after i have already initialized the variable?

You basically have two options:

1) Close the file handle and reopen (you can use the file handles member name if you don't want to hard code it):

>>> fh = open('some.file', 'wb')
>>> fh.write('Some text\n')
>>> fh.close()
>>> fh = open(fh.name, 'rb')
>>> fh.read()
'Some text\n'
>>> fh.close()
>>>

2) Open the file in 'read plus write' mode r+ . This probably isn't your best bet however as you'll need to constantly seek and tell around your file and it's probably more complication than you're looking for.

I think your best bet is to just close it when you're done, and reopen in the mode as needed.

jlm699 320 Veteran Poster

This shouldn't make a difference but the proper way to use the with statement is like so:

with open('C:/Python31/SKUs.txt', 'w') as txtfile:
    num = 817
    while num <= 820:
        x = "G" + str(num)
        txtfile.write(x)
        num += 1

Notice I omit closing the file. That's because the with syntax automatically closes the file handle. AFter that loop you can test with txtfile.closed , which should return True because it's closed.

jlm699 320 Veteran Poster

Okay, I changed it to the following, but when I run it and open the file, the document is still blank.

txtfile = open('C:/Python31/SKUs.txt', 'w')

with txtfile:
    num = 817
    while num <= 820:
        x = "G" + str(num)
        txtfile.write(x)
        num += 1

txtfile.close()

That code works fine for me. What platform are you on?

jlm699 320 Veteran Poster

You'll need to actually write to your file handle txtfile by using txtfile.write( text ) .

jlm699 320 Veteran Poster

I am new to regular expressions, but I do not get why this is not working
:

import re
inputstr = "HI\n//asgwrg\nasdg"
re.sub("\/\/(.*)(\n)", "\n", inputstr)

I am trying to substitute everything between "//" and newline with newline. Can someone tell me whats wrong?

I am using python 3.1

What do you mean by, "it's not working" ? It works fine for me:

>>> import re
>>> inputstr = "HI\n//asgwrg\nasdg"
>>> re.sub("\/\/(.*)(\n)", "\n", inputstr)
'HI\n\nasdg'
>>>

More details please on what doesn't work.

jlm699 320 Veteran Poster

Did this just start or has it happened always? It almost sounds like you may have inadvertently borked your Python install. I'd suggest a clean install.

jlm699 320 Veteran Poster

As little as I can remember 1 mile is about 1.6 km, so 1 km is 1/1.6 miles.

According to the Google:

1 kilometer = 0.621371192 miles

jlm699 320 Veteran Poster

As far as asking the user for input use either raw_input or input depending on your version of Python. Then the conversion is simple math. Just google "1 kilometer to miles" and it will give you the conversion rate.

jlm699 320 Veteran Poster

You can use in to figure out if a list (or string for that matter) contains a particular element:

>>> act_in = "I would love to take alice and punch her in the mouth"
>>> action = act_in.lower().split()
>>> if 'alice' in action:
...     print('This action will be performed on Alice')
... elif 'bob' in action:
...     print('This action will be performed on Bob')
... 
This action will be performed on Alice
>>> if 'punch' in action:
...     print('The target is getting punched')
... elif 'kick' in action:
...     print('The target is getting kicked')
...     
The target is getting punched
>>>

I believe that in simply makes use of the list method index (or analogously string.find ), which returns the index of the element you're looking for, and -1 if it does not exist in the list (string). So in would be the true/false version of using list.index (or string.find ).

So in the above code, splitting the string into a list is unnecessary if you're not using indexing to access individual words. Leave the action as a string and you can just ask if the word you're looking for is in the string.

>>> act_in = 'Sometimes, I like to kick people in the teeth.  One of the people that I frequently kick is named Bob.  That Bob is such an idiot.'
>>> action = act_in.lower()
>>> 'bob' in action
True
>>> 'alice' in action
False
>>> 'punch' in action
False
>>> 'kick' in action
True …
jlm699 320 Veteran Poster

If you were to split the users input into a list you can use list indexing to call out each word individually. Here's an example:

>>> act_in = "punch Alice in the face"
>>> act_in_parts = act_in.split()
>>> action = act_in_parts[0]
>>> target = act_in_parts[1]
>>> action
'punch'
>>> target
'Alice'
>>>
jlm699 320 Veteran Poster

I've been unable to get to it for the last hour or so.

This is a great site to keep in mind when you're posed with this question in the future...

www.downforeveryoneorjustme.com

lllllIllIlllI commented: Ah, i love that site! +4
jlm699 320 Veteran Poster

I'm thinking you should just be "adding" the lists together instead of appending a list onto a list... if you know what I mean.

Like this:

import re

def test():
    a = "<this is> <a> test"
    b = re.split("(<|>)", a)
    c = []
    for item in b:
        c += item.split()
    print(c)

if __name__ == '__main__':
    test()

""" My Output:
['<', 'this', 'is', '>', '<', 'a', '>', 'test']
"""

Is that what you're looking for?

jlm699 320 Veteran Poster

Here's a trick to keep in your back pocket: docs.python.org (note the site is down right now).

That's the absolute best resource for discovering things and answering your questions about Python (next to DaniWeb, naturally!)

And whenever you're confused about the usage of a particular function in Python you can always fire up your interpreter and use help(function) . For example:

Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> my_string = 'foobar'
>>> help(my_string.strip)
Help on built-in function strip:

strip(...)
    S.strip([chars]) -> str

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
>>>

Another thing to keep in mind is that you can query the members and methods of any object (and since everything in Python is an object that means you can query ANYTHING!) using dir. This in combination with help can really get you far when in discovery/test mode.

>>> dir(my_string)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt_
_', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__'
, '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__
rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
 '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'co
unt', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum',
'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'ispr
intable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', '
maketrans', 'partition', 'replace', 'rfind', 'rindex', …
jlm699 320 Veteran Poster
#open inventory and add contents to contents list
    newfile = open("inventory.txt", "rt")
    for item in newfile:
        ## Use strip here to remove the newlines that you're reading in
        contents.append(item.strip())
    newfile.close()

You're right... it's important to remember that when reading files, each line has a newline on the end of it. It's usually a good idea to always use strip() to strip the white space off of the end (as well as the beginning of the line - so if you've got tabs or spaces prepending your text use rstrip to only get the right side of the line clear of white space).

jlm699 320 Veteran Poster

For one thing, don't name your list "list", as that's a reserved word in Python (try list('12345') ), same thing with file... But that modification won't help you.

I'm assuming you've got a new version of Python installed, as the method you're using will only work in earlier versions of python.

pickle.dump(obj, file[, protocol, *, fix_imports=True])¶

Write a pickled representation of obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj).

The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3. The default protocol is 3; a backward-incompatible protocol designed for Python 3.0.

Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced.

The file argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, a io.BytesIO instance, or any other custom object that meets this interface.

If fix_imports is True and protocol is less than 3, pickle will try to map the new Python 3.x names to the old module names used in Python 2.x, so that the pickle data stream is readable with Python 2.x.

That's from the 3.1 docs; note that you must open your files in binary mode now. So for dumping use 'wb', and loading use 'rb'.

jlm699 320 Veteran Poster

don't know how to create a window installer

I've used NSIS to create Windows installers from my py2exe programs in the past.

jlm699 320 Veteran Poster

1. What is the "vs solution" ?
2. How are you performing your "build and clean" ?
3. What isn't creating the .exe ?

jlm699 320 Veteran Poster

Whether you implement pstats in python or perl you'll still have the same problem. You need to learn how to set up/maintain an apache server before you're ever going to get pstats.mycompany.com up and running again.

And no, pstats is a python module. But there are perl wrappers out there.

jlm699 320 Veteran Poster

goto musicback2

I was just talking with a co-worker yesterday about BASIC. He mentioned that people should learn it simply to demonstrate how NOT to write code... heh

Anyway, to call a function you would do this:

>>> def musicback2():
...     print 'Hey this is the music back 2 function'
...     
>>> musicback2()
Hey this is the music back 2 function
>>>

You simply use the name of the function with parenthesis. If your function has any parameters, you'll need to make sure you add those in the parenthesis too.

jlm699 320 Veteran Poster

sqlite3.OperationalError: near "?": syntax error

File "f:\Hosanna\CodeBase\PyCodeBase\sqlite_on_test.py", line 26, in <module>
test.CreateNewTable("testing")
File "f:\Hosanna\CodeBase\PyCodeBase\sqlite_on_test.py", line 12, in CreateNewTable
self.cur.execute("CREATE TABLE IF NOT EXISTS ?(id INTEGER, name TEXT)", (tablename, ))

Yup, that's a syntax error in the SQL command. Read up on SQL syntax here.

jlm699 320 Veteran Poster
import os
os.system("tasklist")

run this script and Get jlm699's flavour

Yes, both tasklist and ps are command line executables in their respective OS. They print out a list of all the running processes. It will still be up to you to read the return and search for your program unless you know how to use grep. Although I'm not sure if windows has a grep-like feature. I'd assume no

jlm699 320 Veteran Poster

Is there a question here?

Also, do you not need to perform a conn.commit() in sqlite after transactions? I know that for postgres it's a req

jlm699 320 Veteran Poster

You should be running py2exe as such: python setup.py py2exe you'll want to make sure you're inside the directory where both files are located.

Also your console item should be: console = [{"script": 'Hello.py'}] )

jlm699 320 Veteran Poster

That means you haven't installed/setup the module correctly. Why don't you try going to the source website and see if there are instructions for setup.

jlm699 320 Veteran Poster
for Origin, Destination, FlightNo, Aircraft, DaysOf, Departure, Arrival, BeginDate, EndDate in csvParser:
    dicts.append({'Origin': Origin, 'Destination': Destination, 'Flight No': FlightNo, 'Aircraft': Aircraft, 'Days Of': DaysOf,
                  'Departure': Departure, 'Arrival': Arrival, 'Begin Date': BeginDate, 'End Date': EndDate})

as it gets to the end of the csv file and there is nothing else to read, so there is a valueError, anyone know how to prevent this?

It would help if you pasted the traceback to know which bit is causing the problem, but here's my suggestion: basically you need to make sure that each line is valid for the number of fields you're unpacking...

Go back to using the for fields in parser: method, and then do a check like this:

if fields and len(fields) == 9:
    Origin, Destination, FlightNo, Aircraft, DaysOf, Departure, Arrival, BeginDate, EndDate = fields
else:
    print 'Invalid line format: %s' % str(fields)
    break

Like I said, it's hard to say that will fix it without the traceback, as I'm not sure what exactly is failing... but this is my suspicion.

I never use the csv module so I don't really know how that iteration process works although I'm surprised it wouldn't raise a StopIteration... Maybe there's extra lines with less fields than you're expecting at the end there... And the unpacking into all those fields is crapping out when there aren't enough values to unpack.

jlm699 320 Veteran Poster

In windows use tasklist , and in linux us ps . In either case, you'll need to search/grep out your process's name to see if it's running