snippsat 661 Master Poster

is 'globals()' a namespace? and does a namespace work like a dictionary in the sense that you can add a key to a dictionary just by:

Yes globals() are a namespace.
A namespace is it`s just like dictionary.

*** Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32. ***
>>> a = 5
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'a': 5,
 'pyscripter': <module 'pyscripter' (built-in)>}
>>> globals()['a']
5
>>> globals()['b'] = 6 #same as b = 6
>>> b
6
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'a': 5,
 'b': 6,
 'pyscripter': <module 'pyscripter' (built-in)>}
>>>

Python has 3 namespaces global namespace, local namespace, built-in namespace .
We can take a look at local namespace.

>>> def foo():
...     x = 'i am local'
...     return x
... 
>>> foo()
'i am local'
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'foo': <function foo at 0x01EE5AF0>,
 'pyscripter': <module 'pyscripter' (built-in)>}

>>> x #if we try to access x
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'x' is not defined

>>> #x are local to fuction foo
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'foo': <function foo at 0x01EE5AF0>,
 'pyscripter': <module 'pyscripter' (built-in)>}

>>> def foo():
...     global x #make x global
...     x = 'i am no longer only local'
...     return x
... …
snippsat 661 Master Poster

There is no problem all python 2.x books/tutorials will works for python 2.7.
It dos not mattter if it`s python 2.4 - 2.5 - 2.6,code will run fine in python 2.7.
New features for python 2.7
http://docs.python.org/dev/whatsnew/2.7.html
Only python 3 break backwardcompatibility.
This post is a good start.
http://www.daniweb.com/software-development/python/threads/20774

snippsat 661 Master Poster

Yes of course didn't think of python 3.
xrange() in python 2.x,same as range() in python 3.
An python 3 has only range() that is returing an iteator.

snippsat 661 Master Poster

Just a note,maybe meant to give more brainwork to call a list on range()
that is returning a list.

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
snippsat 661 Master Poster

Maybe a little confusing that line from richieking.
You should read link from tony because this i basic stuff you shold be able to figure out.

with open('your.txt') as f:
    for item in f:
        from_file = item.split(',')

for line in from_file:
    print line
snippsat 661 Master Poster

Just a note that can help.
New from python 2.7 is collections.Counter

>>> from collections import Counter
>>> l = ['j', 'a', 'n', 'k', 'o', 's', 'i', 'e', 'n', 'a', 'p', 'i', 'v', 'o']
>>> Counter(text)
Counter({'a': 2, 'i': 2, 'o': 2, 'n': 2, 'e': 1, 'k': 1, 'j': 1, 'p': 1, 's': 1, 'v': 1})

It also has a most_common feature.

>>> Counter(text).most_common(5)
[('a', 2), ('i', 2), ('o', 2), ('n', 2), ('e', 1)]
>>>
snippsat 661 Master Poster

So a demo to the other way to install packages,easy_install is good to have and use.
I use easy_install most of the time.

I use same third party packages unidecode in this test.
http://pypi.python.org/pypi/Unidecode/0.04.1
I download Unidecode-0.04.1.tar.gz and pack it out,you pack it out to wherever you want.

Then from cmd i naviagte to the unpacked folder.
The wirte python setup.py install
Now unidecode is installed,test it out.

***Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32. 
>>> import unidecode
>>> dir(unidecode)
['Char',
 'NULLMAP',
 '__builtins__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__path__',
 'unidecode']

>>> unidecode.unidecode(u"\u5317\u4EB0")
'Bei Jing '
>>>
snippsat 661 Master Poster

Tony has explain this,just a little more with code.

def something():
    a = raw_input('>> ')
    return a

print something()

As you something() has the return value.

def something():
    a = raw_input('>> ')
    return a

a = something() #store it in variable a
print a

One important fact with functions is that code local to that function,you have to call it.
That why a is not leaked out in global space.

No it work with making a global,but this is ugly and dont code like this.

def something():
    global a
    a = raw_input('>> ')
    return a

something()
print a
snippsat 661 Master Poster

You have to run kode in same folder as 'newfile.txt' or you have to give correct path.

f = open('c:/somefolder/newfile.txt','r+')

I do not have a
file there, but I thought you created a file with the same code?

Or as tony mention read(r) dos not create a new file only write(w) dos that.

snippsat 661 Master Poster

Convert to string and use len(),is the most commen way.

>>> n = 123
>>> len(str(n))
3
>>>

If your user input is returning a string like raw_input() in python 2.x and input() in python 3.x you can use len().
Then convert to integer if needed.
You can make function that takes integer as argument,and returning the lenght out.
A couple of example.

>>> u = raw_input('Enter a number')
Enter a number
>>> u = raw_input('Enter a number: ')
Enter a number: 123
>>> len(u)
3
>>> int(u) + 123
246

#A function
>>> def lenght(n):
	return len(str(n))

>>> lenght(12345)
5
>>>

Without converting to string.

import math
digits = int(math.log10(12345))+1
print digits #5
snippsat 661 Master Poster

WHat is QT?

QT(first link in google)

python and used pyside to compile it?

Pyside(GUI-toolkit) is a licence free versjon of QT.

You seems not so much uppdatet about this thing,so do a little searching.
Python is an easier language to learn and use than C++,python are used in many areas.
http://www.python.org/about/quotes/

snippsat 661 Master Poster

So then what is python used for if you can't create dekstop programs?

Of course you can create dekstop programs with python,in fact python is very good for that.
You have many good GUI toolkit like wxpython,PyQt,PyGTK.
And the god news for python pyside(no licence problem)
http://www.pyside.org/
You can also use java(swing) and .NET(winform) through python.

Some expample of program using this GUI-toolkit.
VLC(QT)
http://www.videolan.org/vlc/screenshots.html
Wxpython/wxwidgets
Dropbox- TrueCrypt - Digsby

In this link code for all GUI-toolkit.
http://www.daniweb.com/software-development/python/threads/191210

vegaseat commented: good info +15
snippsat 661 Master Poster

You have module like py2exe,cxfreeze,gui2exe that will give you(exe) to run without python installed.
If that what you mean.

snippsat 661 Master Poster
snippsat 661 Master Poster

A little basic stuff about Class/OOP stuff that can be good to now.
Remeber it`s not called a function but a method,when it belong to Class.

class Active(object):
    ''' Special method __init__() is called auto when you makeing a object(acts as Constructor)'''
    def __init__(self):
        self.players = []
        self.goblins = []

    def put_first(self, first):
        '''This look like a function,put when belong to a Class is called a method'''
        return self.goblins.insert(0, first)

    def __str__(self):
        '''Special method __str__  get used when we use print on a object'''
        return 'players: %s goblins: %s' % (self.players, self.goblins)

#Now let test out this Class in IDLE

Here we se two empty list because stuff under __init__ get called auto when we make an object

>>> a_object = Active() #Class instance,we are making a object
>>> print a_object #print find __str__,and print out object info
players: [] goblins: []
>>>

We put in a couple of goblins.

>>> a_object.goblins.append('Grunt')
>>> a_object.goblins.append('Killer')
>>> print a_object
players: [] goblins: ['Grunt', 'Killer']

Last we are using method put_first to place a goblin first in the list.

>>> a_object.put_first('Gotar')
>>> print a_object
players: [] goblins: ['Gotar', 'Grunt', 'Killer']
>>>
snippsat 661 Master Poster

look like it get and error on try to import numpy.
Try. help('numpy') .

Try this.

try:
    help('modules')
except Exception, e:
    print e

Or

try:
    help('modules')
except ImportError:
    pass

To get it to continue after ImportError.

Place for numpy C:\Python27\Lib\site-packages\numpy So you have to delete this folder is reinstall.
Remeber if you reinstall python,can 3 party modules like numpy not be removed.
You have to do it manually.

snippsat 661 Master Poster
snippsat 661 Master Poster

You have just paste code into IDLE(python shell),that dos not work.
Do this file->new window now copy code under and paste code into the new window you got.

print ("Game Over")
input("Press the enter key to exit.")

Save the file with .py extension(somthing.py)
Now you can press F5 or Run Module from the menu.

IDLE(python shell) you can just type in 1 line and you have to hit enter after every line(if test more than line) and you se output immediately and also without print.

>>> print ("Game Over")
Game Over

>>> ("Game Over")
'Game Over'
>>> 
          
>>> for i in range(3):
...     i
...     
0
1
2
   
>>> a = 'hello'
>>> for word in a:
...     word
...     
'h'
'e'
'l'
'l'
'o'
>>>

Get a god editor make it eaiser to run code like pyscripter.
http://code.google.com/p/pyscripter/

Darion commented: Thankss :) +0
snippsat 661 Master Poster

The "is" statement should only be used when you want to check if
something is exactly and identical to None like "a is None" or "b is not None".
For everything else you should use == or !=.
There are some other use cases for "is", too.
But in general you shouldn't use "is".

snippsat 661 Master Poster

in ruby everything is an object, unlike Python where the primitives are, well, primitive

Maybe you should look thing up before you talk.
http://www.diveintopython.org/getting_to_know_python/everything_is_an_object.html

Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute doc, which returns the doc string defined in the function's source code. The sys module is an object which has (among other things) an attribute called path. And so forth.

As with Python, in Ruby,... Everything is an object
http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/
So there you have it from Ruby's own website: in Python everything is an object

.

snippsat 661 Master Poster

There is a bug with python 3.2 and command line output from input()
It put on a '\r' character on input() when run from command line.
http://bugs.python.org/issue11272
This will be fix in in 3.3 (r88530) and 3.2 (r88531). Others versions are not affected.

A temporay fix is to use strip()
guess = input('Your guess\n').strip()

snippsat 661 Master Poster

Just a note,dont use singel \ it can be used as an escape character.
For windows always python C:\\my_script\\script.py or python C:/my_script/script.py

snippsat 661 Master Poster

Just a note collections Counter will always sort in descending count order.
Here i also show most_common(),no we now that all word after 'it' has 1 as count.

from collections import Counter
from string import punctuation

text = """\
If you see a turn signal blinking on a car with a southern license plate,
you may rest assured that it was on when the car car car car car was purchased.
"""

text = ''.join([c for c in text if c not in punctuation])
print Counter(text.split()).most_common(6)
#-->[('car', 6), ('a', 3), ('you', 2), ('was', 2), ('on', 2), ('it', 1)]
vegaseat commented: nice +13
Lardmeister commented: good code +6
e-papa commented: Good one. +1
snippsat 661 Master Poster

Hello. I have been trying to run a simple script in Windows 7 DOS using the python command

Dont call it DOS because it`s a long time since windows had DOS.
Windows 98 is the last version based on MS‑DOS.

Command Prompt is sometimes incorrectly referred to as "the DOS prompt" or as MS-DOS itself. Command Prompt is a Windows program that emulates many of the command line abilities available in MS-DOS but it is not actually MS-DOS.

How do I set PYTHONPATH?

Add PYTHONPATH to Environment Variables.
http://www.windows7hacker.com/index.php/2010/05/how-to-addedit-environment-variables-in-windows-7/
To path add ;C:\python32\;C:\python32\scripts;
If install in other folder than this(default),type in correct path to that folder.
A good python editor make it easier to run code,look at pyscripter.
http://code.google.com/p/pyscripter/

snippsat 661 Master Poster

As tony posted there is much info on this site.
Take a look The Python Standard Library
All this is build-in an you can import and use it.

snippsat 661 Master Poster

I have seen someone else in a other forum had the same problem with python 3.2
Is correct when run from IDLE,and the problem is when run from command line.
This is python bug tracker,if you want to look for or report a bug.
http://bugs.python.org/

snippsat 661 Master Poster

What OS(operating system) do you us?
For windows the brainless binary install(exe,msi) next,next...finish.

List of diffent OS install at pygame site.
http://www.pygame.org/install.html

e-papa commented: good one. +1
snippsat 661 Master Poster

Dont use file as variable is a reserved keyword for python.
So for this script under to work,test.py an words.txt need to be in same folder.

#test.py
my_file = open('words.txt') #Remeber '' open take string as argument
print my_file.read()
my_file.close()

Let say that words.txt is not in same folder as test.py
Then you need to give correct path to words.txt
Here words.txt is placed in folder c:\test
Remeber not use single \ when give path to file,python can see \ as an escape character.
c:\\test or c:/test not c:\test

#test.py
my_file = open('c:/test/words.txt')
print my_file.read()
my_file.close()

The most common way in python today is to use with open()

with open('words.txt') as f:
    print f.read()

With this method you dont need to close() file object,as you see i do in script over.

e-papa commented: Thanks +1
snippsat 661 Master Poster

but is there any python equivalent to the Java .jar files?

Yes .py files.
So think of this jar files will not work if not JRE (Java Runtime Environment) is installed.
To make jar files you need JDK (Java Development Kit)

Py files will not work if python is not installed.
Jus the same as with jar files.

Is there any way to produce an executable file containing everything within it like Java's .jar's?

jar are not executable without java installed,just the same as .py files is not executable without python installed.

snippsat 661 Master Poster

http://stackoverflow.com/questions/3270209/how-do-i-make-tkinter-support-png-transparency
Wxpython has good support for transparent image,and may be a better choice.
For me there has never been a choice i find wxpython much better than Tkinter.
The ugly look of Tkinter in windows is not ok at all.
PyQt and pyGTK shold also has support for this.

snippsat 661 Master Poster

Use urlretrieve .

>>> from urllib import urlretrieve
>>> help(urlretrieve)
Help on function urlretrieve in module urllib:

urlretrieve(url, filename=None, reporthook=None, data=None)

Example.

from urllib import urlretrieve
urlretrieve('http://gdimitriou.eu/wp-content/uploads/2008/04/google-image-search.jpg', 'google-image-search.jpg')
debasishgang7 commented: It worked fine..Thanks a lot.. +2
snippsat 661 Master Poster

A couple way is split at / or use a regex.

>>> d = '1/2/2010'.split('/')[2]
>>> d
'2010'

>>> import re
>>> s = re.search(r'\d{4}', '1/2/2010')
>>> s.group()
'2010'
>>>
snippsat 661 Master Poster

You are doing some some thing that are not good at all.
assert lin == "Acatari, Aiud, 72.639\n"
Read about the use of assert and that you use == make it strange¨.
assert <<expression, error_message>> is a form of error checking.
It raises an exception if the expression evaluates to false and include the error message.

If you want to convert back to tuple it look like this.
I think you should do some basic reading about python.

def line_to_entry(lin):
    lin = tuple(lin.split(', '))
    return lin

if __name__ ==  "__main__":
    lin = "Acatari, Aiud, 72.639\n"
    print line_to_entry(lin)
snippsat 661 Master Poster

Or i got it again confused?

It`s right and you could use an other name so it`s not entry as an function argument an a variable name.

def entry_to_line(tuple_in):
    entry = ', '.join(map(str,tuple_in))
    return entry

#re = ('Acatari', 'Aiud', 72.639)
test = (1,2,3)
print entry_to_line(test)
print type(entry_to_line(test))
snippsat 661 Master Poster

Using tonyjv'advice i tried the fallowing with the code for the first function

You are making some big mistake when you making it a fuction.
You are putting in an argument to function that you not use inside the function entry
And you making a recursive call of the function return entry_to_line .

def entry_to_line():
    re = ('Acatari', 'Aiud', 72.639)
    entry = ', '.join(map(str,re))
    return entry

print entry_to_line()

#Or with list comprehension
def entry_to_line():
    re = ('Acatari', 'Aiud', 72.639)
    entry = ', '.join([str(i) for i in re])
    return entry

print entry_to_line()

or the second one i tried to find a way to convert from string to tuples for he first time in shell

No you are not it is a tuple and you are using a tuple.

>>> a = ('Acatari', 'Aiud', 72.639)
>>> type(a)
<type 'tuple'>

>>> b = ', '.join(map(str, ('Acatari', 'Aiud', 72.639)))
>>> type(b)
<type 'str'>
>>> b
'Acatari, Aiud, 72.639'

>>> c = ', '.join([str(i) for i in ('Acatari', 'Aiud', 72.639)])
>>> type(c)
<type 'str'>
>>> c
'Acatari, Aiud, 72.639'
>>>
snippsat 661 Master Poster

The problem in python 3 code is that you are comparing integer with string. input() in python 3 return a string same as raw_input() in python 2. input() in python 2 return an integer.
This will work

answer = int(input("> ")) #make input return an integer

Or you can cast it to an integer later.

if int(x) == 1:

Read about the differnce.
http://diveintopython3.org/porting-code-to-python-3-with-2to3.html

Use 4 space as indentation in your code,not 8.

vegaseat commented: nice +13
snippsat 661 Master Poster

TreeCtrl is really not meant to interact with filesystem.
wx.FileDialog is used to display files.

snippsat 661 Master Poster

This way in my code will save it in format you want.

with open('new_file.txt', 'w') as f:
    f.write('\n'.join(l))
snippsat 661 Master Poster

Here is one way.

import re

'''num.txt-->
name2,number2;name3,number3;name1,number1
'''

with open('num.txt') as f:
    l = [i.strip().split(';') for i in f][0]

print l  #Test print

def key_sort(string):
    result = re.split(r'(\d+)', string)
    for i in xrange(1, len(result), 2):
        result[i] = int(result[i])
    return result

l.sort(key=key_sort)
print l

"""Output-->
['name2,number2', 'name3,number3', 'name1,number1']
['name1,number1', 'name2,number2', 'name3,number3']
"""
snippsat 661 Master Poster

I dont use Tkinter so much,wxpyhon is my favoritt gui-toolkit in python.
You can look at this post here show sneekula and vega the use of tkinter listbox.
http://www.daniweb.com/forums/thread191210-2.html

snippsat 661 Master Poster

Look at cgi module.
http://docs.python.org/library/cgi.html
http://www.tutorialspoint.com/python/python_cgi_programming.htm

Most common way to work with HTML/websites is to use one of python Web framework.
http://wiki.python.org/moin/WebFrameworks

snippsat 661 Master Poster

Look into regular expression for changing filename.
Here is an example.

import re

files = '''\
lovelyname_annoying_chars.txt
Diename_annoying_charshard.txt
somenamename_annoying_chars.txt'''

new_files = re.sub(r'name_annoying_chars', '', files)
print new_files

"""Output-->
lovely.txt
Diehard.txt
somename.txt
"""
snippsat 661 Master Poster

Python string are immutable so delete it wont work.
You can replace it first character with nothing ''.

>>> s = "this is a really long string that is completely pointless. But hey who cares!"
>>> s.replace(s[0], '')
'his is a really long sring ha is compleely poinless. Bu hey who cares!'

Another way is make it a list and the do stuff you need,and take it back into a string again.

>>> s = "this is a really long string that is completely pointless. But hey who cares!"
>>> s = list(s)  #Make it a list
>>> del(s[0])    #Delete first character
>>> ''.join(s)   #Take it back to a string
'his is a really long string that is completely pointless. But hey who cares!'
snippsat 661 Master Poster

Look at the output -ordi-
fiss gisse hd uc tb oa z
Do you see some character are missing?

I dont know how BirdaoGwra want the output,here are a couple of way.
fissgiss is one word in this,some more work is neede to split that to.
Pickle is way to save and get same output back,look at this.
http://www.daniweb.com/forums/thread343685.html

l = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

with open('w.txt', 'w') as f:
    f.writelines(''.join(i) + ' ' for i in l)
#--> fissgiss eh du ct bo az 

#---------------------------------------#
l = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

with open('w.txt', 'w') as f:
    f.writelines(''.join(i) + '\n' for i in l)

"""Output-->
fissgiss
eh
du
ct
bo
az
"""

Edit did see you post about output.

l = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

with open('w.txt', 'w') as f:
    f.writelines(' '.join(i) + '\n' for i in l)

"""Output-->
fiss giss
e h
d u
c t
b o
a z
"""
BirdaoGwra commented: I learned from him. +2
snippsat 661 Master Poster

Something you can look at,for doing financial calculations look at Decimal module.
http://docs.python.org/library/decimal.html

>>> number = 0.60
>>> print '%.2f' % number
0.60

>>> from decimal import *
>>> Decimal('0.60')
Decimal('0.60')
>>> Decimal('0.60') + Decimal('0.60')
Decimal('1.20')
>>> 
>>> print Decimal('0.60') + Decimal('0.60')
1.20
Archenemie commented: This post was concise and to the point with good examples +2
snippsat 661 Master Poster

thanks. What are major differences using Iron Python vs Python 2.6.6?

With ironpython you can use the .Net(framework)library.
Same as Jython there you can use java library.
You write in python,and import from Net library.

IronPython is an implementation of the Python programming language running under .NET and Silverlight. It supports an interactive console with fully dynamic compilation. It's well integrated with the rest of the .NET Framework and makes all .NET libraries easily available to Python programmers, while maintaining compatibility with the Python language. There also is Visual Studio tooling integration.

snippsat 661 Master Poster

I have been told by a number of people to use xpath instead of regex for some of my regex searches.

What are you searching?

Some notes about XML/webpages here is regex not the right tool.
If you are parsing(searching) XML/html you should use beautifulsoup / lxml(has XPath built in) that is designed exactly for this purpose.

Why is regex bad for xml/html read this very good answer.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

snippsat 661 Master Poster

When I run it, I have to type

setup py2exe

You run it as every other python code.
From your editor or command line python name_of_script.py

snippsat 661 Master Poster

Dident get you pysnmp script to work.
Here is a working py2exe kode.

from distutils.core import setup
import py2exe
import sys

def py_exe(file_in=None):
    if len(sys.argv) == 1:
        sys.argv.append('py2exe')

    setup(options = {'py2exe': {'compressed': 1, 'optimize': 2, 'ascii': 1, 'bundle_files': 3}},
           zipfile = None,

           ## Can use console or window
           ## Filpath to '....py' or same folder as you run this py file from
           console = [{'script': 'your_script.py'}])
py_exe()

You can also try Gui2exe.
http://code.google.com/p/gui2exe/

snippsat 661 Master Poster

You should(most) read some tutorials/book about using classes.
The way you are doing is not god at all and wrong.
Like basic thing that a class need the self keyword.

Can write an example that makes more sense.

class numbers(object):
    def addition(self,a,b):
        self.a = a
        self.b = b
        return self.a + self.b

    def multiply(self,a,b):
        self.a = a
        self.b = b
        return self.a * self.b

class main(numbers):
    calc = numbers()
    num1 = 5
    num2 = 10
    print calc.addition(num1, num2) #15
    print calc.multiply(num1, num2) #50