Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread jfong
Chris Angelico at 2015/12/26  UTC+8 5:50:07PM wrote:
> 11: Another normal assignment, because otherwise the rest of the work
> is pointless. :)

Thanks for this detailed example. As I had learned so far, Python really take 
"name" seriously, and every meaningful result you got have to assign to a name 
at last. This morning I played some codes on the http://pythonturor.com and 
found out that every objects which was not created at top-level of a module or 
in a class will disappear after import. A very "unusual" view. 

> Python's flexibility and simplicity are a huge part of why I love the
> language so much.

simplicity? Maybe because you are s familiar with Python. It's not to me, 
at least at this moment. Please see my next question follows.

--Jach
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread jfong
Last night I noticed that Python does not resolve name in "def" during import, 
as C does in the compile/link stage, it was deferred until it was referenced 
(i.e. codes was executed). That's OK for Anyway codes has to be debugged sooner 
or later. I just have to get used to this style.

But check these codes, it seems not.
---
x = 1  # a global variable
print(x)

class Test:
x = 4  # a class attribute
print(x)
def func(self):
print(x)

x1 = Test()
x1.x = 41  # a instance's attribute
x1.func()  # it's 1 but 41 was expect:-(


--Jach
-- 
https://mail.python.org/mailman/listinfo/python-list


A newbie quesiton: local variable in a nested funciton

2015-12-25 Thread jfong
As a tranditional language programmer like me, the result is really weird.

Here is the test codes in file test1.py:

def outerf():
counter = 55
def innerf():
print(counter)
#counter += 1
return innerf

myf = outerf()


the result is:

>>> import test1
>>> test1.myf()
55
>>>


that's OK. But if I un-comment the line "counter += 1", then it gives me this:

>>> import test1
>>> test1.myf()
Traceback (most recent call last):
  File "", line 1, in 
  File "D:\Work\Python34\test1.py", line 41, in innerf
print(counter)
UnboundLocalError: local variable 'counter' referenced before assignment
>>> 


In the first situation, the local variable 'counter' can be referenced 
correctly. But in the second, why a statement added after the print() statement 
can makes this variable "disappear", even the print() won't do the right thing. 
Isn't it wired? please help!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: OT: citizens and countries - was Re: v3.5.1 - msi download

2015-12-23 Thread jfong
Michael Torrie at 2015/12/23  UTC+8 12:22:23PM wrote:
> In the American way of thinking, the country *is* the people.  So it was
> neither a lie nor a bad thing that Kennedy proclaimed.  Maybe this is
> not true for other countries, but I think most Americans would feel it
> is true for their country.  And indeed the sentiment that Kennedy
> expressed resonates deeply with many/most Americans. A country is only
> made great by citizens willing to do many things for the good of the
> country and their fellow citizens.

I don't think any country can be "great" if it can't even take care of its own 
people well. American can not be great because of there are millions of 
citizens has no enough food, health cares and living on the street, at the same 
time this country spend billions of dollars on bombing other country's people.

This situation is painful to human mind and it was supposed to be solved by the 
country leaders. But politicians are incapable of doing anything except been 
good on spreading glorious words and sentences. As an anaesthetic to divert 
people from this incapability, these words also make some Americans happy to 
ignore the facts and continuously to believe that American is still a great 
country.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: v3.5.1 - msi download

2015-12-22 Thread jfong
Mark Lawrence at 2015/12/21 UTC+8 8:50:00PM wrote:
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.

When I saw this sentence, I can't resist to think of the famous lie created by 
president John kennedy: "Ask not what your country can do for you, ask what you 
can do for your country".

A COUNTRY WAS BUILT TO SERVE THE PEOPLE!!!

Do you think people are so boring that they have to build a country to serve to?

But there is always a bunch of idiots lost in these gorgeous words, don't even 
take a single moment to think of it, completely forgot the purpose of what a 
country was built for. The means eventually become the object, and millions of 
millions idiots sacrifice their life for this imaginary object.

A LANGUAGE WAS BUILT TO SERVE THE USER!!!


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


Problem on ctypes arguments in a DLL function

2015-12-18 Thread jfong
I am trying to use the libusb-win32 v1.2.6.0 with Win7. I wrote a test 
program(showing below) but stuck with a strange problem. Here is the result:

D:\Work\Python34>python
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import libusb_u2aTest as u2a
0x10c4
0x1
Traceback (most recent call last):
  File "", line 1, in 
  File "D:\Work\Python34\libusb_u2aTest.py", line 364, in 
pHDL = _lib.usb_open(pDevice)
ValueError: Procedure probably called with too many arguments (4 bytes in excess
)
>>>
-
I replace the troubled line with a "pass" to make the loading success, then to 
check the type of "pDevice", it's correct.

>>> u2a.pDevice


It seems no reason that this call can be in trouble:-( Any hint was 
appreciated. Thanks ahead.


libusb_u2aTest.py listing:
-
from ctypes import *
_lib = windll.LoadLibrary("C:\\Windows\\System32\\libusb0.dll")

_PATH_MAX = 512

### Data structures...
class _usb_device_descriptor(Structure):
_fields_ = [('bLength', c_uint8),
('bDescriptorType', c_uint8),
('bcdUSB', c_uint16),
('bDeviceClass', c_uint8),
('bDeviceSubClass', c_uint8),
('bDeviceProtocol', c_uint8),
('bMaxPacketSize0', c_uint8),
('idVendor', c_uint16),
('idProduct', c_uint16),
('bcdDevice', c_uint16),
('iManufacturer', c_uint8),
('iProduct', c_uint8),
('iSerialNumber', c_uint8),
('bNumConfigurations', c_uint8)]

class _usb_device(Structure): pass
class _usb_bus(Structure): pass
_usb_device._fields_ = [('next', POINTER(_usb_device)),
('prev', POINTER(_usb_device)),
('filename', c_int8 * _PATH_MAX),
('bus', POINTER(_usb_bus)),
('descriptor', _usb_device_descriptor),
#('config', POINTER(_usb_config_descriptor)), # not 
implemented yet
('config', POINTER(c_int)),  # to ease this test
('dev', c_void_p),
('devnum', c_uint8),
('num_children', c_ubyte),
('children', POINTER(POINTER(_usb_device)))]

_usb_bus._fields_ = [('next', POINTER(_usb_bus)),
('prev', POINTER(_usb_bus)),
('dirname', c_char * _PATH_MAX),
('devices', POINTER(_usb_device)),
('location', c_uint32),
('root_dev', POINTER(_usb_device))]

_usb_dev_handle = c_void_p


### Function prototype...
# struct usb_bus *usb_get_busses(void);
_lib.usb_get_busses.restype = POINTER(_usb_bus)

# usb_dev_handle *usb_open(struct usb_device *dev);
_lib.usb_open.argtypes = [POINTER(_usb_device)]
_lib.usb_open.restype = _usb_dev_handle


### Test start...
_lib.usb_init()
_lib.usb_find_busses()
_lib.usb_find_devices()
pBus = _lib.usb_get_busses()
if bool(pBus):
pDevice = pBus[0].devices
if bool(pDevice):
print(hex(pDevice[0].descriptor.idVendor))
print(hex(pDevice[0].descriptor.idProduct))

if pDevice[0].descriptor.idVendor == 0x10c4 and \
   pDevice[0].descriptor.idProduct == 0x0001:
pHDL = _lib.usb_open(pDevice)  # <--this line is in trouble

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


Re: Problem on ctypes arguments in a DLL function

2015-12-18 Thread jfong
eryk sun at 2015/12/18  UTC+8 6:26:02PM wrote:
> The function's calling convention is x86 cdecl (CDLL, caller stack
> cleanup), but you're using the x86 stdcall convention (WinDLL, callee
> stack cleanup). For a 64-bit process they're actually the same, but
> you're using 32-bit Python, so you have to pay attention to the
> convention.
> 
> > _lib = windll.LoadLibrary("C:\\Windows\\System32\\libusb0.dll")
> 
> It should simply be
> 
> _lib = CDLL('libusb0')
> 
> windll/WinDLL is the wrong calling convention. Everything else is just
> a waste of keystrokes. windll.LoadLibrary is an inferior way to call
> WinDLL, since it can't pass constructor arguments such as use_errno or
> use_last_error. The System32 directory is on the DLL search path, and
> Windows will add the .dll extension for you.
> 
> The calling convention is declared in the header file lusb0_usb.h [1].
> For example:
> 
> struct usb_bus *usb_get_busses(void);
> 
> Notice there's no mention of __stdcall there, so it's using the
> default cdecl convention.

Hi! eryk, thank you very much. No idea how long I will take to get out of this 
gutter if not have your hint. I should pay more attention on keyword __stdcall 
in the header file.

> > _usb_dev_handle = c_void_p
> 
> You'll be better off using
> 
> class _usb_dev_handle(Structure):
> pass
> 
> _usb_dev_handle_p = POINTER(_usb_dev_handle)
> 
> This provides stronger type safety. c_void_p is too permissive. It's
> easier to debug a ctypes ArgumentError than a memory access violation
> or data corruption.
> 
> [1]: 
> http://sourceforge.net/p/libusb-win32/code/413/tree/trunk/libusb/src/lusb0_usb.h

I think I am still in the kindergarten, not enter the gate of python school 
yet:-( much things to learn.


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


Python 3.4 + pyUSB 1.0 + libusb-win32 1.2.6.0, what happens?

2015-12-05 Thread jfong
I am new to python. I had a USB HID device which behavior is that the host send 
a 64 bytes commands to it, after complete the execution of this commands it 
send back a 64 bytes status to the host, so the host can check the status and 
decide the next step.

When I run it under Win7 with SwiftForth 3.5.9 (a Forth system) and 
libusb-win32 1.2.6.0, it performs well. But when I test it under the same PC 
with python 3.4, pyUSB 1.0 and libusb-win32 1.2.6.0, it performs a little 
strange. The status read back always fail at the first time (return zero 
length) and success at the second time.

>>> dev.write(0x02, cmdBuf)
64
>>> dev.read(0x81, 64, 5000)
array('B')# no data returned
>>> dev.read(0x81, 64, 5000)
array('B', [165, 0, ])# this one is correct, totally 64 bytes

another "strange" thing is that I had a 5000 timeout in the read but I see no 
delay at the first read. It returns immediately. I suppose it should wait for 5 
seconds long before it returns. Right?

Any hint?

Best Regards,
Jach Fong

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


Re: python response slow when running external DLL

2015-12-01 Thread jfong
Peter Otten at 2015/12/1  UTC+8 7:01:55PM wrote:
> While the var_status.set() invoked from the second thread modifies some 
> internal data the main thread could kick in and modify (parts of) that same 
> data, thus bringing tkinter into an broken state. A simple example that 
> demonstrates the problem:
> 
> import random
> import threading
> import time
> 
> account = 70
> 
> def withdraw(delay, amount):
> global account
> if account >= amount:
> print("withdrawing", amount)
> account -= amount
> else:
> print("failed to withdraw", amount)
> 
> threads = []
> for i in range(10):
> t = threading.Thread(
> target=withdraw,
> kwargs=dict(delay=.1,
> amount=random.randrange(1, 20)))
> threads.append(t)
> t.start()
> 
> for t in threads:
> t.join()

It's a simple and vivid example. You must be in the banking business:-)

In this exercise, I can just use update_idletasks() method to solve the 
deferred display problem of tkinter, and forget all about thread. But what if I 
really want to use thread for the long-running DLL function in the download 
hander? I didn't figure out a correct way of doing it at this moment. Maybe 
queue is the answer but I am not familiar with it yet.

def download():
var_status.set(...)  #showing a start-up message
result = SayHello()  #this is a long-running function
if result#according to the result, display more messages

> 
> Before every withdrawal there seems to be a check that ensures that there is 
> enough money left, but when you run the script a few times you will still 
> sometimes end with a negative balance. That happens when thread A finds 
> enough money, then execution switches to thread B which also finds enough 
> money, then both threads perform a withdrawal -- oops there wasn't enough 
> money for both.
>  
> >> Another complication that inevitably comes with concurrency: what if the
> >> user triggers another download while one download is already running? If
> >> you don't keep track of all downloads the message will already switch to
> >> "Download OK" while one download is still running.
> > 
> > Hummm...this thought never comes to my mind. After take a quick test I
> > found, you are right, a second "download" was triggered immediately.
> > That's a shock to me. I suppose the same event shouldn't be triggered
> > again, or at least not triggered immediately, before its previous handler
> > was completed. ...I will take a check later on Borland C++ builder to see
> > how it reacts!
> > 
> > Anyway to prevent this happens? if Python didn't take care it for us.
> 
> A simple measure would be to disable the button until the download has 
> ended.

Good! simple and work.

I shouldn't say "Python should take care of it", but "tk" should do. It's 
annoying the widget's command was re-triggered before it was finished. (my 
personal opinion:-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python response slow when running external DLL

2015-11-30 Thread jfong
jf...@ms4.hinet.net at 2015/11/29  UTC+8 10:55:28AM wrote:
> > > .
> > > .
> > > #do the rest
> > > var_status.set('Download...')
> > > _thread.start_new_thread(td_download, ())  #must use threading
> > > 
> > > def td_download():
> > > result = mydll.SayHello()
> > > if result:
> > > var_status.set("Download Fail at %s" % hex(result))
> > > showerror('Romter', 'Download Fail')
> > > else:
> > > var_status.set('Download OK')
> > > showinfo('Romter', 'Download OK')
> > 
> > As td_download() runs in the other thread the var_status.set() methods are 
> > problematic.
> 
> No idea what kind of problem it will encounter. Can you explain?

It might be not a good idea to update GUI in a spawned thread, according to 
Mark Lutz's book "Programming Python", section "Using Threads with tkinter GUIs"

"If you do use threads in tkinter programs, however, you need to remember that 
only the main thread (the one that built the GUI and started the mainloop) 
should generally make GUI calls. At the least, multiple threads should not 
attempt to update the GUI at the same time..." 
 
> > Another complication that inevitably comes with concurrency: what if the 
> > user triggers another download while one download is already running? If 
> > you 
> > don't keep track of all downloads the message will already switch to 
> > "Download OK" while one download is still running.
> 
> Hummm...this thought never comes to my mind. After take a quick test I found, 
> you are right, a second "download" was triggered immediately. That's a shock 
> to me. I suppose the same event shouldn't be triggered again, or at least not 
> triggered immediately, before its previous handler was completed. ...I will 
> take a check later on Borland C++ builder to see how it reacts!
> 
> Anyway to prevent this happens? if Python didn't take care it for us.

then don't use thread if you prefer the GUI freeze.

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


Re: python response slow when running external DLL

2015-11-28 Thread jfong
Peter Otten at 2015/11/28 UTC+8 6:14:09PM wrote:
> No, the point of both recipes is that tkinter operations are only ever 
> invoked from the main thread. The main thread has polling code that 
> repeatedly looks if there are results from the helper thread. As far I 
> understand the polling method has the structure
> 
> f():
># did we get something back from the other thread?
># a queue is used to avoid race conditions
> 
># if yes react.
># var_status.set() goes here
> 
># reschedule f to run again in a few millisecs; 
># that's what after() does

Have no idea how the main thread poll on all those events (or it use a queue)?
All I know now is that the main thread(mainloop()?) can be easily blocked by 
event handlers if the handler didn't run as a separate thread.

> > .
> > .
> > #do the rest
> > var_status.set('Download...')
> > _thread.start_new_thread(td_download, ())  #must use threading
> > 
> > def td_download():
> > result = mydll.SayHello()
> > if result:
> > var_status.set("Download Fail at %s" % hex(result))
> > showerror('Romter', 'Download Fail')
> > else:
> > var_status.set('Download OK')
> > showinfo('Romter', 'Download OK')
> 
> As td_download() runs in the other thread the var_status.set() methods are 
> problematic.

No idea what kind of problem it will encounter. Can you explain?

> Another complication that inevitably comes with concurrency: what if the 
> user triggers another download while one download is already running? If you 
> don't keep track of all downloads the message will already switch to 
> "Download OK" while one download is still running.

Hummm...this thought never comes to my mind. After take a quick test I found, 
you are right, a second "download" was triggered immediately. That's a shock to 
me. I suppose the same event shouldn't be triggered again, or at least not 
triggered immediately, before its previous handler was completed. ...I will 
take a check later on Borland C++ builder to see how it reacts!

Anyway to prevent this happens? if Python didn't take care it for us.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python response slow when running external DLL

2015-11-28 Thread jfong
Laura Creighton at 2015/11/28 UTC+8 6:52:25PM wrote:
> I never saw the reply that Peter is replying to.
> The threading module constructs a higher level interface on top of the
> low level thread module.  Thus it is the preferred way to go for
> standard Python code -- and even Fredrik's recipe contains the
> line:
>   import thread # should use the threading module instead!
> 
> Laura
Hi! Laura, 

takes the porting of an old BCB GUI program as an exercise in my learning 
python, I just quickly grab the required tools (mainly the tkinter) in python 
to complete this "work" and get a feeling of how python performs on doing this. 
Most of my knowledge of python comes from Mark Lutz's book "Learning python" 
and "Programming python". I didn't dive into this language deeply yet. There 
are topics about "_thread" and "threading" modules in the book and I just pick 
the lower level one for this because the "threading" is based on the "_thread".

Thanks for your note and link.

--Jach


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


Re: python response slow when running external DLL

2015-11-27 Thread jfong
Peter Otten at 2015/11/27  UTC+8 5:19:17 PM wrote:

Hi! Peter, thanks for your prompt reply.

> What does var_status.set() do? If it writes to stdout you may just need to 
> flush().

   var_status is a StringVar which binds to a lable's textvariable. I use this 
label as the status bar to show message.

> Do you see the same behaviour when you replace mydll.SayHello() with 
> something simple like time.sleep(1)?

I use time.sleep(3) to replace mydll.SayHello(), still get the same.

> As a general remark keep your test scripts as simple as possible. Example: 
> If 
> 
> import mydll
> print("Download...", end="")
> mydll.SayHello()
> print("OK")
> 
> showed the same behaviour it would be the ideal test script.

I run the above statements in a test file, it works as expected. I can see 
"Download..." and then "OK".


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


Re: python response slow when running external DLL

2015-11-27 Thread jfong
Peter Otten at 2015/11/27 UTC+8 8:20:54PM wrote:

> Quick-fix example:
> def download():
> var.set("Starting download...")
> root.update_idletasks()
> time.sleep(3)
> var.set("... done")

Thanks, Peter, The update_idletasks() works. In my trivial program it's easy to 
apply for there are only two places call the DLL function.

> A cleaner solution can indeed involve threads; you might adapt the approach 
> from  (Python 2 code).

Using thread is obviously more logical. I think my mistake was the "while busy: 
 pass" loop which makes no sense because it blocks the main thread, just as the 
time.sleep() does. That's why in your link (and Laura's too) the widget.after() 
scheduling was used for this purpose.

From what I had learned here, the other way I can do is making the codes 
modified as follows. It will get ride of the "result" and "busy" global 
variables, but it also makes the codes looks a little ugly. I think I will take 
the update_idletasks() way in this porting for it seems more simpler, and can 
be used on thread or non-thread calling. Thank you again.
.
.
#do the rest
var_status.set('Download...')
_thread.start_new_thread(td_download, ())  #must use threading

def td_download():
result = mydll.SayHello()
if result:
var_status.set("Download Fail at %s" % hex(result))
showerror('Romter', 'Download Fail')
else:
var_status.set('Download OK')
showinfo('Romter', 'Download OK')

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


python response slow when running external DLL

2015-11-26 Thread jfong
I am new to Python. As an exercise of it, I try to port a program which was 
written more than 10 years ago. This program use the Borland C++ Builder as its 
GUI front end and a DLL does the real work(it will takes a few seconds to 
complete). I saw a strange phenomenon in the following codes. The 
"var_status.set('Download...')" statement seems was deferred and didn't show up 
until the external DLL job was finished and I can only saw the result of 
"var_status.set('Download OK')" statement which immediately follows. I try to 
do the DLL function in a thread(selected by using the "test" flag in codes), 
but it didn't help.

Can anyone tell me what's the point I was missed?

-
def download():
global iniFilename
if test:  global result, busy
ini = iniFilename
iniFilename = "c:\\$$temp.in3"
saveIniFile()
iniFilename = ini
#do the rest
var_status.set('Download...')
if not test:
result = mydll.SayHello()
else:
busy = True
_thread.start_new_thread(td_download, ())
while busy:  pass
if result:
var_status.set("Download Fail at %s" % hex(result))
showerror('Romter', 'Download Fail')
else:
var_status.set('Download OK')
showinfo('Romter', 'Download OK')

if test:
result = 0x
busy = True
def td_download():
global busy, result
result = mydll.SayHello()
busy = False
--

Best Regards,
Jach
-- 
https://mail.python.org/mailman/listinfo/python-list


<    1   2   3