Re: matplotlib basemap colorbar exception : Given element not contained in the stack
在 2022年5月30日星期一 UTC+8 03:29:28, 写道: > On 2022-05-29 13:57, iMath wrote: > > please see the formated code at > > https://stackoverflow.com/questions/72423464/matplotlib-basemap-colorbar-exception-given-element-not-contained-in-the-stack > The problem might be that you're passing "ax=self.ax" when you create > the basemap, and you have: > > self.ax = self.map_canvas.figure.subplots() > > According to the docs, ".subplots" doesn't return the axes, it returns a > _tuple_ of the figure and the axes. Thanks for your reply ! But as I printed the value of self.ax , it is actually an instance of AxesSubplot. -- https://mail.python.org/mailman/listinfo/python-list
Re: matplotlib basemap colorbar exception : Given element not contained in the stack
please see the formated code at https://stackoverflow.com/questions/72423464/matplotlib-basemap-colorbar-exception-given-element-not-contained-in-the-stack -- https://mail.python.org/mailman/listinfo/python-list
Re: recover pickled data: pickle data was truncated
Thanks for all your kind help, wish you a promising year! -- https://mail.python.org/mailman/listinfo/python-list
Re: recover pickled data: pickle data was truncated
在 2021年12月30日星期四 UTC+8 03:13:21, 写道: > On Wed, 29 Dec 2021 at 18:33, iMath wrote: > > But I found the size of the file of the shelve data didn't change much, so > > I guess the data are still in it , I just wonder any way to recover my data. > I agree with Barry, Chris and Avi. IMHO your data is lost. Unpickling > it by hand is a harsh work and maybe unreliable. > > Is there any reason you can't simply add a semaphore to avoid writing > at the same time and re-run the code and regenerate the data? Thanks for your replies! I didn't have a sense of adding a semaphore on writing to pickle data before, so corrupted the data. Since my data was colleted in the daily usage, so cannot re-run the code and regenerate the data. In order to avoid corrupting my data again and the complicity of using a semaphore, now I am using json text to store my data. -- https://mail.python.org/mailman/listinfo/python-list
Re: recover pickled data: pickle data was truncated
> You have lost the data in that case. But I found the size of the file of the shelve data didn't change much, so I guess the data are still in it , I just wonder any way to recover my data. -- https://mail.python.org/mailman/listinfo/python-list
recover pickled data: pickle data was truncated
Normally, the shelve data should be read and write by only one process at a time, but unfortunately it was simultaneously read and write by two processes, thus corrupted it. Is there any way to recover all data in it ? Currently I just get "pickle data was truncated" exception after reading a portion of the data? Data and code here :https://drive.google.com/file/d/137nJFc1TvOge88EjzhnFX9bXg6vd0RYQ/view?usp=sharing -- https://mail.python.org/mailman/listinfo/python-list
Re: celery multi celery.exceptions.TimeoutError: The operation timed out
在 2020年9月21日星期一 UTC+8 下午8:02:44, 写道: > Op 21-09-2020 om 12:14 schreef iMath: > > Asked 3 days ago at > > https://stackoverflow.com/questions/63951696/celery-multi-celery-exceptions-timeouterror-the-operation-timed-out > > > > > > But nobody helped yet, anyone ? > > > Did you see > https://stackoverflow.com/questions/9769496/celery-received-unregistered-task-of-type-run-example > > ? > > The error says "Received unregistered task of type 'proj.tasks.add'", so > it looks very much like your registry is not correct/complete. > > Vriendelijke groeten/Kind regards, > > Menno Hölscher None of the answers helped . Finally ,I switched to https://github.com/jarekwg/django-apscheduler I found it is elegant and easy to use -- https://mail.python.org/mailman/listinfo/python-list
celery multi celery.exceptions.TimeoutError: The operation timed out
Asked 3 days ago at https://stackoverflow.com/questions/63951696/celery-multi-celery-exceptions-timeouterror-the-operation-timed-out But nobody helped yet, anyone ? -- https://mail.python.org/mailman/listinfo/python-list
celery multi celery.exceptions.TimeoutError: The operation timed out
I followed the official [Celery guide](https://docs.celeryproject.org/en/stable/getting-started/next-steps.html#in-the-background) to learn, everything works well when using `celery -A proj worker -l info` to start the worker, however , if I run the worker in the background using `celery multi restart w1 -A proj -l info --logfile=./celery.log`, then I got >>> from proj.tasks import add >>> add.delay().get(timeout=19) Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.8/dist-packages/celery/result.py", line 230, in get return self.backend.wait_for_pending( File "/usr/local/lib/python3.8/dist-packages/celery/backends/base.py", line 660, in wait_for_pending meta = self.wait_for( File "/usr/local/lib/python3.8/dist-packages/celery/backends/base.py", line 696, in wait_for raise TimeoutError('The operation timed out.') celery.exceptions.TimeoutError: The operation timed out. >>> So what's wrong ? Test environment : - Python 3.8.2 - celery multi v4.4.7 - rabbitmqctl version --->3.8.2 and Project layout ([code files](https://github.com/celery/celery/files/5231502/proj.zip)): > proj/__init__.py > /celery.py > /tasks.py celery.py from __future__ import absolute_import, unicode_literals from celery import Celery app = Celery('proj', broker='amqp://localhost', # backend='db+sqlite:///results.sqlite', # The backend argument, If you don’t need results, it’s better to disable them. Results can also be disabled for individual tasks by setting the @task(ignore_result=True) option. include=['proj.tasks']) # The include argument is a list of modules to import when the worker starts. You need to add our tasks module here so that the worker is able to find our tasks. app.conf.CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite' if __name__ == '__main__': app.start() tasks.py from __future__ import absolute_import, unicode_literals from .celery import app import datetime @app.task def add(): return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") The log info as the following , I googled , but didn't find a working solutions ``` [2020-09-15 22:10:03,229: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2020-09-15 22:10:03,238: INFO/MainProcess] mingle: searching for neighbors [2020-09-15 22:10:04,260: INFO/MainProcess] mingle: all alone [2020-09-15 22:10:04,273: INFO/MainProcess] w1@iZwz962a07bhoio77q4ewxZ ready. [2020-09-15 22:10:10,625: ERROR/MainProcess] Received unregistered task of type 'proj.tasks.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/celery/worker/consumer/consumer.py", line 562, in on_task_received strategy = strategies[type_] KeyError: 'proj.tasks.add' ``` -- https://mail.python.org/mailman/listinfo/python-list
find all js/css/image pathnames in a HTML document
To find all js/css/image pathnames in a HTML document, I used regular expression(in the last line of my code snippet) to do this as the following, are there any other shorter regular expressions or more efficient ways to do this ? import re translation=''' bee·tle™ / ˈbiːtl ; NAmE ˈbiːtl / noun , verb beetle beetles beetled beetling noun 1 an insect, often large and black, with a hard case on its back, covering its wings. There are several types of beetle. 甲虫 ☞see also death-watch beetle 2 Beetle ( NAmE also bug ) the English names for the original Volkswagen small car with a round shape at the front and the back “甲壳虫”(英国人用以指称一款圆头圆顶的原大众牌的小汽车) verb [intransitive ] + adv./prep. ( BrE) ( informal) to move somewhere quickly 快速移动 SYN scurry ◆ I last saw him beetling off down the road. 我上次见到他时,他正快步沿路而去。 bee·tle™ / ˈbiːtl ; NAmE ˈbiːtl / ''' print(re.findall(r'(?:href|src)="([^"]+?\.(?:css|js|png|jpg))"', translation)) -- https://mail.python.org/mailman/listinfo/python-list
Re: right way to use zipimport, zipimport.ZipImportError: not a Zip file
Not works on Windows >>> import sys >>> sys.path.insert(0, >>> 'C:/Users/i/Downloads/you-get-0.4.1128.zip/you-get-0.4.1128/src') >>> from you_get import common Traceback (most recent call last): File "", line 1, in from you_get import common ModuleNotFoundError: No module named 'you_get' >>> -- https://mail.python.org/mailman/listinfo/python-list
Re: right way to use zipimport, zipimport.ZipImportError: not a Zip file
I think someone gives the true reason caused the exception here https://stackoverflow.com/a/51821910/1485853 Thanks to his explanation , I extracted the zip archive and then add the extracted to a zip archive using Bandizip, this time `zipimport.zipimporter(r'C:\Users\i\Downloads\you-get-0.4.1128.zip') ` doesn't give the exception , but still cannot import the module, even adding the `.zip` file to `sys.path`, >>> import sys >>> sys.path.insert(0, r'C:\Users\i\Downloads\you-get-0.4.1128.zip\you-get-0.4.1128\src') >>> from you_get import common Traceback (most recent call last): File "", line 1, in from you_get import common ModuleNotFoundError: No module named 'you_get' >>> >>> import zipimport >>> z=zipimport.zipimporter(r'C:\Users\i\Downloads\you-get-0.4.1128.zip\you-get-0.4.1128\src') >>> z >>> z.load_module('you_get.common') Traceback (most recent call last): File "", line 1, in z.load_module('you_get.common') zipimport.ZipImportError: can't find module 'you_get.common' >>> z.load_module('you_get') Traceback (most recent call last): File "", line 1, in z.load_module('you_get') zipimport.ZipImportError: can't find module 'you_get' What I actually want to do is to use the module in a pyinstaller frozen application , I also need to upgrade the module to latest version whenever needed , I cannot find a solution yet. -- https://mail.python.org/mailman/listinfo/python-list
Re: right way to use zipimport, zipimport.ZipImportError: not a Zip file
I think someone gives the true reason caused the exception here https://stackoverflow.com/a/51821910/1485853 Thanks to his explanation , I extracted the zip archive and then add the extracted to a zip archive using Bandizip, this time `zipimport.zipimporter(r'C:\Users\i\Downloads\you-get-0.4.1128.zip') ` doesn't give the exception , but still cannot import the module, even adding the `.zip` file to `sys.path`, >>> import sys >>> sys.path.insert(0, r'C:\Users\i\Downloads\you-get-0.4.1128.zip\you-get-0.4.1128\src') >>> from you_get import common Traceback (most recent call last): File "", line 1, in from you_get import common ModuleNotFoundError: No module named 'you_get' >>> >>> import zipimport >>> z=zipimport.zipimporter(r'C:\Users\i\Downloads\you-get-0.4.1128.zip\you-get-0.4.1128\src') >>> z >>> z.load_module('you_get.common') Traceback (most recent call last): File "", line 1, in z.load_module('you_get.common') zipimport.ZipImportError: can't find module 'you_get.common' >>> z.load_module('you_get') Traceback (most recent call last): File "", line 1, in z.load_module('you_get') zipimport.ZipImportError: can't find module 'you_get' What I actually want to do is to use the module in a pyinstaller frozen application , I also need to upgrade the module to latest version whenever needed , I cannot find a solution yet. -- https://mail.python.org/mailman/listinfo/python-list
right way to use zipimport, zipimport.ZipImportError: not a Zip file
The same question also posted here https://stackoverflow.com/questions/51820473/right-way-to-use-zipimport-zipimport-zipimporterror-not-a-zip-file I have managed to use [this module][1] without installation - just import it from path to use , import sys url = 'https://example.com' sys.path.insert(0, r'C:\Users\i\Downloads\you-get-0.4.1128\src') # from you_get import common common.any_download(url, info_only=True)#NoneType It seems possible in Python to use `zipimport` to directly use the zip archive of the module without extraction, I wonder what is the right way to use `zipimport`, a simple trying like the following just gives the exception . I downloaded the file from [here][2] , the file `C:\Users\i\Downloads\you-get-0.4.1128.zip` does exist and isn't corrupted. >>> import zipimport >>> zipimport.zipimporter(r'C:\Users\i\Downloads\you-get-0.4.1128.zip') Traceback (most recent call last): File "", line 1, in zipimport.zipimporter(r'C:\Users\i\Downloads\you-get-0.4.1128.zip') zipimport.ZipImportError: not a Zip file: 'C:\\Users\\i\\Downloads\\you-get-0.4.1128.zip' >>> [1]: https://github.com/soimort/you-get/releases [2]: https://github.com/soimort/you-get/archive/v0.4.1128.zip -- https://mail.python.org/mailman/listinfo/python-list
Re: send PIL.Image to django server side and get it back
Thanks, I solved it finally stackoverflow.com/a/51453785/1485853 -- https://mail.python.org/mailman/listinfo/python-list
send PIL.Image to django server side and get it back
I also posted the question here https://stackoverflow.com/questions/51355926/send-pil-image-to-django-server-side-and-get-it-back I don't know what's under the hood of sending an image from client side to server side, so stuck by the following scenario. I want to send a PIL.Image object to django server side using the Python requests lib and get it back in order to use the PIL.Image object on server side. As I have tested , if sent the PIL.Image object without any conversion , that is r = requests.post(SERVER_URL, data={ 'image': PILimage,#PILimage is of type PIL.Image 'wordPos':(86,23) }, ) then I just got a str object with value on server side, I guess it was caused by requests, which converted the PIL.Image object to a str object before sending, so why requestsdo the conversion ? why cannot we send the PIL.Image object without any conversion over the Internet ? please give some explanation here, thanks! -- https://mail.python.org/mailman/listinfo/python-list
Re: using HTTPHandler cause Django server side shows http 400 and Invalid HTTP_HOST header message
On Tuesday, April 11, 2017 at 12:00:27 AM UTC+8, iMath wrote: > > Are you sure you posted the code you are actually using? Because the > > error message suggests a difference. > > > I am sure ! > > As I have tested: If I pass the IP address of my web server to the host > parameter of HTTPHandler, the server side would show http 400 and Invalid > HTTP_HOST header message , Besides the http 400 and Invalid HTTP_HOST header message , there are also exceptions , pasted here https://bpaste.net/show/f2d2e64e7a7e -- https://mail.python.org/mailman/listinfo/python-list
Re: using HTTPHandler cause Django server side shows http 400 and Invalid HTTP_HOST header message
On Tuesday, April 11, 2017 at 12:00:27 AM UTC+8, iMath wrote: > > Are you sure you posted the code you are actually using? Because the > > error message suggests a difference. > > > I am sure ! > > As I have tested: If I pass the IP address of my web server to the host > parameter of HTTPHandler, the server side would show http 400 and Invalid > HTTP_HOST header message , > Besides the http 400 and Invalid HTTP_HOST header message , there are also following exceptions Invalid HTTP_HOST header: '112.74.98.187:8001,112.74.98.187'. The domain name pr ovided is not valid according to RFC 1034/1035. [10/Apr/2017 15:38:04] "GET /VideoParser/lYYDownloaderClientLog/?funcName=%3Cmod ule%3E&lineno=26&levelname=ERROR&name=__main__&stack_info=None&args=%28%29&modul e=a&pathname=C%3A%5CUsers%5Ci%5CDocuments%5CTencent+Files%5C2281570025%5CFileRec v%5Ca.py&process=6636&thread=6972&created=1491838715.9931207&msecs=993.120670318 6035&msg=testing+remote+logging&exc_info=None&relativeCreated=64.00370597839355& filename=a.py&threadName=MainThread&processName=MainProcess&levelno=40&exc_text= None HTTP/1.1" 400 66752 Traceback (most recent call last): File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 180, in finish_respo nse self.write(data) File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 279, in write self._write(data) File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 453, in _write result = self.stdout.write(data) File "/usr/local/lib/python3.6/socketserver.py", line 775, in write self._sock.sendall(b) ConnectionResetError: [Errno 104] Connection reset by peer [10/Apr/2017 15:38:04] "GET /VideoParser/lYYDownloaderClientLog/?funcName=%3Cmod ule%3E&lineno=26&levelname=ERROR&name=__main__&stack_info=None&args=%28%29&modul e=a&pathname=C%3A%5CUsers%5Ci%5CDocuments%5CTencent+Files%5C2281570025%5CFileRec v%5Ca.py&process=6636&thread=6972&created=1491838715.9931207&msecs=993.120670318 6035&msg=testing+remote+logging&exc_info=None&relativeCreated=64.00370597839355& filename=a.py&threadName=MainThread&processName=MainProcess&levelno=40&exc_text= None HTTP/1.1" 500 59 Exception happened during processing of request from ('117.136.84.223', 49862) Traceback (most recent call last): File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 180, in finish_respo nse self.write(data) File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 279, in write self._write(data) File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 453, in _write result = self.stdout.write(data) File "/usr/local/lib/python3.6/socketserver.py", line 775, in write self._sock.sendall(b) ConnectionResetError: [Errno 104] Connection reset by peer During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 141, in run self.handle_error() File "/usr/local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 95, in handle_error super(ServerHandler, self).handle_error() File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 368, in hand
Re: using HTTPHandler cause Django server side shows http 400 and Invalid HTTP_HOST header message
> Are you sure you posted the code you are actually using? Because the > error message suggests a difference. > I am sure ! As I have tested: If I pass the IP address of my web server to the host parameter of HTTPHandler, the server side would show http 400 and Invalid HTTP_HOST header message , while if I pass the domain name instead, then the view function works as expected . would it be a bug within HTTPHandler? -- https://mail.python.org/mailman/listinfo/python-list
Introducing my Python/PyQt5 powered Bing wallpaper open source project
Hello everyone , I'd like to introduce my Python/PyQt5 powered Bing wallpaper open source project. â ï BingNiceWallpapers https://github.com/redstoneleo/BingNiceWallpapers BingNiceWallpapers can get background images from http://www.bing.com/?mkt=zh-CN and set them as your desktop wallpaper by just a single click on system tray icon. For Windows binary installer and more information, please refer to http://mathjoy.lofter.com/post/42208d_7cabcf7 (written in simplified Chinese) Features Changing wallpaper in a single click on system tray icon or after a specified time interval Windows and Linux Gnome desktop support Delete or save the current wallpaper Welcome to help with the project ! -- https://mail.python.org/mailman/listinfo/python-list
Introducing my Python/PyQt5 powered Bing wallpaper open source project
Hello everyone , I'd like to introduce my Python/PyQt5 powered Bing wallpaper open source project. BingNiceWallpapers https://github.com/redstoneleo/BingNiceWallpapers BingNiceWallpapers can get background images from http://www.bing.com/?mkt=zh-CN and set them as your desktop wallpaper by just a single click on system tray icon. For Windows binary installer and more information, please refer to http://mathjoy.lofter.com/post/42208d_7cabcf7 (written in simplified Chinese) Features Changing wallpaper in a single click on system tray icon or after a specified time interval Windows and Linux Gnome desktop support Delete or save the current wallpaper Welcome to help with the project ! -- https://mail.python.org/mailman/listinfo/python-list
python3 - set '\n\n' as the terminator when writing a formatted LogRecord
Is it possible to set '\n\n' as the terminator when writing a formatted LogRecord to a stream by changing the format parameter of logging.basicConfig? I know it is possible using the terminator attribute of StreamHandler class to implement this, I just wonder Is it possible to achieve this feature by changing the format parameter? I am not familiar with the format string language -- https://mail.python.org/mailman/listinfo/python-list
filesystem encoding 'strict' on Windows
the doc of os.fsencode(filename) says Encode filename to the filesystem encoding 'strict' on Windows, what does 'strict' mean ? -- https://mail.python.org/mailman/listinfo/python-list
Re: easy way to return a list of absolute file or directory path within a directory
On Wednesday, September 7, 2016 at 4:00:31 PM UTC+8, Steven D'Aprano wrote: > On Wednesday 07 September 2016 17:08, iMath wrote: > > > Any easier solutions on returning a list of absolute file or directory path > > within a directory? Mine is > > > > list(map(lambda entry: os.path.join(directory,entry),os.listdir(directory))) > > > Use a list comprehension: > > > [os.path.join(directory,entry) for entry in os.listdir(directory)] > > > > -- > Steven > > git gets easier once you get the basic idea that branches are homeomorphic > endofunctors mapping submanifolds of a Hilbert space. yes, a list comprehension does make the code more readable -- https://mail.python.org/mailman/listinfo/python-list
easy way to return a list of absolute file or directory path within a directory
Any easier solutions on returning a list of absolute file or directory path within a directory? Mine is list(map(lambda entry: os.path.join(directory,entry),os.listdir(directory))) -- https://mail.python.org/mailman/listinfo/python-list
Re: index for regex.search() beyond which the RE engine will not go.
On Friday, August 19, 2016 at 10:09:19 PM UTC+8, Steve D'Aprano wrote: > On Fri, 19 Aug 2016 09:14 pm, iMath wrote: > > > > > for > > regex.search(string[, pos[, endpos]]) > > The optional parameter endpos is the index into the string beyond which > > the RE engine will not go, while this lead me to believe the RE engine > > will still search on till the endpos position even after it returned the > > matched object, is this Right ? > > No. > > Once the RE engine finds a match, it stops. You can test this for yourself > with a small timing test, using the "timeit" module. > > from timeit import Timer > huge_string = 'aaabc' + 'a'*100 + 'dea' > re1 = r'ab.a' > re2 = r'ad.a' > > # set up some code to time. > setup = 'import re; from __main__ import huge_string, re1, re2' > t1 = Timer('re.search(re1, huge_string)', setup) > t2 = Timer('re.search(re2, huge_string)', setup) > > # Now run the timers. > best = min(t1.repeat(number=1000))/1000 > print("Time to locate regex at the start of huge string:", best) > best = min(t2.repeat(number=1000))/1000 > print("Time to locate regex at the end of the huge string:", best) > > > > When I run that on my computer, it prints: > > Time to locate regex at the start of huge string: 4.9710273742675785e-06 > Time to locate regex at the end of the huge string: 0.0038938069343566893 > > > So it takes about 4.9 microseconds to find the regex at the beginning of the > string. To find the regex at the end of the string takes about 3893 > microseconds. > > > The "endpos" parameter tells the RE engine to stop at that position if the > regex isn't found before it. It won't go beyond that point. > > > > > > > -- > Steve > “Cheer up,” they said, “things could be worse.” So I cheered up, and sure > enough, things got worse. Thanks for clarifying -- https://mail.python.org/mailman/listinfo/python-list
Re: use regex to search the page one time to get two types of Information
On Friday, August 19, 2016 at 9:45:08 PM UTC+8, Friedrich Rentsch wrote: > On 08/19/2016 09:02 AM, iMath wrote: > > I need to use regex to search two types of Information within a web page, > > while it seems searching the page two times rather than one is much time > > consuming , is it possible to search the page one time to get two or more > > types of Information? > > >>> r = re.compile ('page|Information|time') > >>> r.findall ( (your post) ) > ['Information', 'page', 'page', 'time', 'time', 'page', 'time', > 'Information'] > > Does that look right? > > Frederic I found starting the second search from the first match.endpos does reduce the time consuming, with less time consuming than your solution ,thanks anyway ! -- https://mail.python.org/mailman/listinfo/python-list
Re: use regex to search the page one time to get two types of Information
On Friday, August 19, 2016 at 9:19:22 PM UTC+8, Chris Angelico wrote: > On Fri, Aug 19, 2016 at 11:13 PM, iMath wrote: > > 1. searching the page two times rather than one is a little bit time > > consuming . > > Have you measured that? If not, ignore it. You're searching a web > page; if you're downloading that before you search it, chances are > very good that you spend far more time waiting for the download than > you ever will on the regex. > > ChrisA tested, searching the page two times rather than one is a little bit time consuming . -- https://mail.python.org/mailman/listinfo/python-list
Re: use regex to search the page one time to get two types of Information
1. searching the page two times rather than one is a little bit time consuming . 2. starting the second search from the first match.endpos does reduce the time consuming . 3. how to combine both patterns into one regex? while using the special | regex operator only matches one regex not both -- https://mail.python.org/mailman/listinfo/python-list
index for regex.search() beyond which the RE engine will not go.
for regex.search(string[, pos[, endpos]]) The optional parameter endpos is the index into the string beyond which the RE engine will not go, while this lead me to believe the RE engine will still search on till the endpos position even after it returned the matched object, is this Right ? -- https://mail.python.org/mailman/listinfo/python-list
Re: use regex to search the page one time to get two types of Information
each regex only has one matched result in the web page -- https://mail.python.org/mailman/listinfo/python-list
use regex to search the page one time to get two types of Information
I need to use regex to search two types of Information within a web page, while it seems searching the page two times rather than one is much time consuming , is it possible to search the page one time to get two or more types of Information? -- https://mail.python.org/mailman/listinfo/python-list
get a certain request url during Loading a web page
During Loading this web page(http://www.iqiyi.com/v_19rrkkri8k.html) , the browser makes many requests,now I need a certain request url (e.g.starts with 'http://cache.video.qiyi.com/vms?') during the Loading process ,and the request is made on condition that the adobe flash player plugin for NPAPI is enabled , so any way to get the url via python ? P.S. Better to show some code, I am new to this area. -- https://mail.python.org/mailman/listinfo/python-list
Re: Win32 API in pywin32
On Friday, August 5, 2016 at 7:50:28 AM UTC+8, jj0ge...@gmail.com wrote: > According to Python.org Mark Hammond has an Add-on (pywin32) that supports > Win32 and COM. > > Does anyone know if the Add-on covers all Win32 API functions, and if not is > there a list of the subset of Win32 API functions it does include? > > J. According to my experience , pywin32 doesn't covers all Win32 API functions but most of them , so for these not supported functions, you could resort to ctypes ,and there seems no list of the subset of Win32 API functions it does include. You can contact with the developers of pywin32 using the mailing list python-wi...@python.org -- https://mail.python.org/mailman/listinfo/python-list
Design an encrypted time-limited API on Client/Server side
I am planning design an encrypted time-limited API on both Client and Server sides, the server side is written in Django, the client side is a GUI program which call the API by import requests c = requests.post("http://127.0.0.1:8000/VideoParser/";, data={'videoUrl': videoUrl }) The way it call the API is desperately exposed to those who can use network traffic capturing tools like wireshark and fiddler, while I don't want anyone else could call the API with their customized videoUrl, and if people made the post call with the same parameters 2 minutes later after the client initially made the call, the call should be valid or expired, so how to design the encrypted time-limited API on both Client and Server side in this case ? P.S. I think add an identifier to the post data could prevent them using the API import requests c = requests.post("http://127.0.0.1:8000/VideoParser/";, data={'videoUrl': videoUrl, 'identifier':value_of_identifier }) provided there is something encrypted in the value_of_identifier and it changes with each call, but I don't know how to get started, any idea ? It would be better to show some code , I really don't know which modules to use and how to start to write code. -- https://mail.python.org/mailman/listinfo/python-list
Re: get Coursera video download link via program
I know the two packages : BeautifulSoup and requests may help, I am also able to login in Coursera via requests, the difficulty is how to find out the video download link from the page. -- https://mail.python.org/mailman/listinfo/python-list
get Coursera video download link via program
I want extract Coursera video download link via program(mainly Python) behind those links https://www.coursera.org/learn/human-computer-interaction/lecture/s4rFQ/the-interaction-design-specialization https://www.coursera.org/learn/calculus1/lecture/IYGhT/why-is-calculus-going-to-be-so-much-fun After red a lot of articles about this, still cannot find a way to extract the video download link via program, anyone can offer a step by step solution of extracting the video download link ? Thanks! P.S. I know this project , https://github.com/coursera-dl/coursera but the code is so complex , so I dropped out. -- https://mail.python.org/mailman/listinfo/python-list
Re: Survey -- Move To Trash function in Python?
在 2015年5月14日星期四 UTC+8下午11:45:38,Steven D'Aprano写道: > I'd like to do a little survey, and get a quick show of hands. > > How many people have written GUI or text-based applications or scripts where > a "Move file to trash" function would be useful? > > Would you like to see that in the standard library, even if it meant that > the library had feature-freeze and could gain no more functionality? > > > -- > Steven Send2Trash is a small package that sends files to the Trash https://pypi.python.org/pypi/Send2Trash I am using PyQt, I would like to see that in the standard library -- https://mail.python.org/mailman/listinfo/python-list
cx_Freeze:Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings'
I downloaded cx_Freeze from here, installed it successfully on Ubuntu following this thread . After run python3 setup.py build in cx_Freeze/samples/simple,then change the dir to cx_Freeze/samples/simple/build/exe.linux-i686-3.4,run the following command ,I got the error ?7?4 exe.linux-i686-3.4 ./hello Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' [1]3950 abort ./hello ?7?4 exe.linux-i686-3.4 any idea on fixing this issue ?-- https://mail.python.org/mailman/listinfo/python-list
Re: Future of python on android
在 2014年12月25日星期四UTC+8下午11时31分24秒,Fetchinson .写道: > Hi all, > > I was using sl4a for quite some time on android and it basically > worked very well although some features are missing. It looks like > sl4a is dead, although I could be wrong. Does anyone knowledgeable > have any further info on the future of sl4a? For instance it doesn't > work with android 5 and there doesn't seem to be any activity around > it for the past couple of years. > > If sl4a is out, what's the preferred way of running python on android? > Guido is still working at google, right? This makes me suspect that > python is ought to be part of the android ecosystem but can't find > anything else beyond sl4a. > > So what's the future proof way of writing/deploying/installing python > programs on android? > > Cheers, > Daniel > > > -- > Psss, psss, put it down! - http://www.cafepress.com/putitdown According this post here, http://plashless.wordpress.com/2014/08/19/using-pyqtdeploy0-5-on-linux-to-cross-compile-a-pyqt-app-for-android/ you can use PyQt5 for Android app development ! -- https://mail.python.org/mailman/listinfo/python-list
Re: encrypt the http request url on the local machine
在 2014年12月9日星期二UTC+8下午2时58分36秒,iMath写道: > my software on the local machine needs to send http request to a specific web > server , is there any way to protect the http request url from being found by > Packet analyzer software like Wireshark and fiddler. The sever is not mine, > so I can do nothing in the server . > > It would be better to show some code, I am an absolutely newbie in encryption > . After some retinking on my question ,I found what I am really want is not let any other guys using packet analyzer software know the server name (host name) my software is sending data to . so I translate the host name to IP address format, it somewhat hides the host name. Another question is : for common sites, is the IP address under the host name hardly changing ? -- https://mail.python.org/mailman/listinfo/python-list
Re: beautifulsoup VS lxml
在 2014年12月12日星期五UTC+8上午10时19分56秒,Michael Torrie写道: > On 12/11/2014 07:02 PM, iMath wrote: > > > > which is more easy and elegant for pulling data out of HTML? > > Beautiful Soup is specialized for HTML parsing, and it can deal with > badly formed HTML, but if I recall correctly BeautifulSoup can use the > lxml engine under the hood, so maybe it's the way to go for you, is it > gives you the most flexibility. It certainly has a good API that's easy > to use for data scraping. Try it and see if it's acceptable. tried it, very elegant and Pythonic. thank you very much !!! -- https://mail.python.org/mailman/listinfo/python-list
Re: PyQt: user interface freezed when using concurrent.futures.ThreadPoolExecutor
在 2014年12月11日星期四UTC+8下午1时25分41秒,Michael Torrie写道: > On 12/10/2014 09:52 PM, iMath wrote: > > I think the user interface shouldn't be freezed when using > > concurrent.futures.ThreadPoolExecutor here,as it executes > > asynchronously , but it doesn't meet my expectations,anyone can > > explain why ? any other solutions here to not let user interface > > freezed? > > > > code is here > > http://stackoverflow.com/questions/27393533/user-interface-freezed-when-using-concurrent-futures-threadpoolexecutor > > In most any GUI framework, regardless of your use of threads, your > callbacks must return control to the main loop immediately (whether an > on-click or an on-timer event), or the GUI *will* freeze. > > You are spawning threads to download the urls, then sitting there > waiting for them to finish in the callback. Of course the GUI will > freeze; your callback is blocking it. What you should be doing is > spawning the threads to do the download, then have the threads (using a > proper QThread mechanism or some other semaphore mechanism) raise a > signal to indicate they are done, which you will then catch in the main > loop as a normal callback. And really when it comes to I/O and GUIs, > asynchronous calls are always better than threads. Not sure what Qt has > in the way of asynchronous i/o calls, and I'm not familiar enough with > the various async i/o frameworks in Python to speak to that, though I > did use Python-Twisted once... very powerful once you get your head > wrapped around it. > > Look through the list archives because in the last 3 or 4 weeks I and > another Python user talked proper thread use with PyQt or PySide, with > code examples. "when it comes to I/O and GUIs, asynchronous calls are always better than threads." I cannot grasp your meaning here, IMO, asynchronous calls are done by using threads. -- https://mail.python.org/mailman/listinfo/python-list
beautifulsoup VS lxml
which is more easy and elegant for pulling data out of HTML? -- https://mail.python.org/mailman/listinfo/python-list
PyQt: user interface freezed when using concurrent.futures.ThreadPoolExecutor
I think the user interface shouldn't be freezed when using concurrent.futures.ThreadPoolExecutor here,as it executes asynchronously , but it doesn't meet my expectations,anyone can explain why ? any other solutions here to not let user interface freezed? code is here http://stackoverflow.com/questions/27393533/user-interface-freezed-when-using-concurrent-futures-threadpoolexecutor -- https://mail.python.org/mailman/listinfo/python-list
Re: encrypt the http request url on the local machine
在 2014年12月9日星期二UTC+8下午2时58分36秒,iMath写道: > my software on the local machine needs to send http request to a specific web > server , is there any way to protect the http request url from being found by > Packet analyzer software like Wireshark and fiddler. The sever is not mine, > so I can do nothing in the server . > > It would be better to show some code, I am an absolutely newbie in encryption > . thank you all, I have learnt a lot from your answers. for my question here, I don't want to use a route or proxy or Tor, network access speed is also vital in my application, so perhaps there is no solution. -- https://mail.python.org/mailman/listinfo/python-list
Re: encrypt the http request url on the local machine
在 2014年12月9日星期二UTC+8下午2时58分36秒,iMath写道: > my software on the local machine needs to send http request to a specific web > server , is there any way to protect the http request url from being found by > Packet analyzer software like Wireshark and fiddler. The sever is not mine, > so I can do nothing in the server . > > It would be better to show some code, I am an absolutely newbie in encryption > . I don't know any form of encryption that the server _does_ support, the sever is not mine. Here I just don't want to any other guys using packet analyzer software know which server my software is sending data to -- https://mail.python.org/mailman/listinfo/python-list
Re: encrypt the http request url on the local machine
在 2014年12月9日星期二UTC+8下午2时58分36秒,iMath写道: > my software on the local machine needs to send http request to a specific web > server , is there any way to protect the http request url from being found by > Packet analyzer software like Wireshark and fiddler. The sever is not mine, > so I can do nothing in the server . > > It would be better to show some code, I am an absolutely newbie in encryption > . P.S the server doesn't support https protocol -- https://mail.python.org/mailman/listinfo/python-list
encrypt the http request url on the local machine
my software on the local machine needs to send http request to a specific web server , is there any way to protect the http request url from being found by Packet analyzer software like Wireshark and fiddler. The sever is not mine, so I can do nothing in the server . It would be better to show some code, I am an absolutely newbie in encryption . -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
在 2013年12月6日星期五UTC+8下午10时59分43秒,Chris Angelico写道: > On Sat, Dec 7, 2013 at 1:54 AM, iMath wrote: > > > fp=tempfile.NamedTemporaryFile(delete=False) > > > fp.write(("file '"+fileName1+"'\n").encode('utf-8')) > > > fp.write(("file '"+fileName2+"'\n").encode('utf-8')) > > > > > > > > > subprocess.call(['ffmpeg', '-f', 'concat','-i',fp.name, '-c', 'copy', > > fileName]) > > > fp.close() > > > > You need to close the file before getting the other process to use it. > > Otherwise, it may not be able to open the file at all, and even if it > > can, you might find that not all the data has been written. > > > > But congrats! You have successfully found the points I was directing > > you to. Yes, I was hinting that you need NamedTemporaryFile, the .name > > attribute, and delete=False. Good job! > > > > ChrisA we don't have permission to use the temporary file while it has not been closed,but when the file is closed , it will be destroyed by default(delete=True),but once we set delete=False,then we couldn't depend on the convenience of letting the temporary file automatically delete itself after it has been used(then we have to delete it later by os.remove()) ,thus there is nearly no convenience in creating a temporary file or a persistent one when using NamedTemporaryFile. I think this is a design flaw and should be improved like this :when delete=True,the file should be removed upon destruction of the object or on function return or on garbage collected,only when delete=False,the file can remain on the disk . -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
在 2013年12月4日星期三UTC+8下午6时51分49秒,Chris Angelico写道: > On Wed, Dec 4, 2013 at 8:38 PM, Andreas Perstinger > wrote: > > > "fp" is a file object, but subprocess expects a list of strings as > > > its first argument. > > > > More fundamentally: The subprocess's arguments must include the *name* > > of the file. This means you can't use TemporaryFile at all, as it's > > not guaranteed to return an object that actually has a file name. > > > > There's another problem, too, and that's that you're not closing the > > file before expecting the subprocess to open it. And once you do that, > > you'll find that the file no longer exists once it's been closed. In > > fact, you'll need to research the tempfile module a bit to be able to > > do what you want here; rather than spoon-feed you an exact solution, > > I'll just say that there is one, and it can be found here: > > > > http://docs.python.org/3.3/library/tempfile.html > > > > ChrisA I think you mean I should create a temporary file by NamedTemporaryFile(). After tried it many times, I found there is nearly no convenience in creating a temporary file or a persistent one here ,because we couldn't use the temporary file while it has not been closed ,so we couldn't depend on the convenience of letting the temporary file automatically delete itself when closing, we have to delete it later by os.remove() after it has been used in that command line. code without the with statement is here ,but it is wrong ,it shows this line c:\docume~1\admini~1\locals~1\temp\tmp0d8959: Invalid data found when processing input fp=tempfile.NamedTemporaryFile(delete=False) fp.write(("file '"+fileName1+"'\n").encode('utf-8')) fp.write(("file '"+fileName2+"'\n").encode('utf-8')) subprocess.call(['ffmpeg', '-f', 'concat','-i',fp.name, '-c', 'copy', fileName]) fp.close() -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
在 2013年12月6日星期五UTC+8下午5时23分59秒,Mark Lawrence写道: > On 06/12/2013 06:23, iMath wrote: > > > > Dearest iMath, wouldst thou be kind enough to partake of obtaining some > > type of email client that dost not sendeth double spaced data into this > > most illustrious of mailing lists/newsgroups. Thanking thee for thine > > participation in my most humble of requests. I do remain your most > > obedient servant. > > > > -- > > My fellow Pythonistas, ask not what our language can do for you, ask > > what you can do for our language. > > > > Mark Lawrence yes ,I am a native Chinese speaker.I always post question by Google Group not through email ,is there something wrong with it ? your english is a little strange to me . -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
在 2013年12月4日星期三UTC+8下午5时38分27秒,Andreas Perstinger写道: > iMath wrote: > > >I use the following code to do the test ,but error occurred ,it > > >prompts system cannot find specified files ,but the files are indeed > > >exists there ,any help ? > > > > > >with tempfile.TemporaryFile() as fp: > > >fp.write(("file '"+'a1.mp3'+"'\n").encode('utf-8')) > > >fp.write(("file '"+'a2.mp3'+"'\n").encode('utf-8')) > > > > > >subprocess.call(['ffmpeg/ffmpeg', '-f', 'concat','-i',fp, '-c', > > > 'copy', 'a3.mp3']) > > > > Basic rule: Always copy'n'paste the exact traceback you get. > > > > I don't think you are running the code you have posted because your > > subprocess call doesn't work: > > > > >>> import tempfile, subprocess > > >>> with tempfile.TemporaryFile() as fp: > > ... subprocess.call(["foo", "bar", fp, "baz"]) > > ... > > Traceback (most recent call last): > > File "", line 2, in > > File "/usr/lib/python3.3/subprocess.py", line 520, in call > > with Popen(*popenargs, **kwargs) as p: > > File "/usr/lib/python3.3/subprocess.py", line 820, in __init__ > > restore_signals, start_new_session) > > File "/usr/lib/python3.3/subprocess.py", line 1380, in _execute_child > > restore_signals, start_new_session, preexec_fn) > > TypeError: Can't convert '_io.BufferedRandom' object to str implicitly > > > > "fp" is a file object, but subprocess expects a list of strings as > > its first argument. > > > > Bye, Andreas sorry for my fuss. it prompts StdErr: -c: No such file or directory -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
在 2013年12月3日星期二UTC+8上午9时42分11秒,rusi写道: > On Tuesday, December 3, 2013 6:45:42 AM UTC+5:30, iMath wrote: > > > so is there any way to create a temporary file by Python here ? > > > > http://docs.python.org/2/library/tempfile.html I use the following code to do the test ,but error occurred ,it prompts system cannot find specified files ,but the files are indeed exists there ,any help ? with tempfile.TemporaryFile() as fp: fp.write(("file '"+'a1.mp3'+"'\n").encode('utf-8')) fp.write(("file '"+'a2.mp3'+"'\n").encode('utf-8')) subprocess.call(['ffmpeg/ffmpeg', '-f', 'concat','-i',fp, '-c', 'copy', 'a3.mp3']) -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
在 2013年12月3日星期二UTC+8上午9时42分11秒,rusi写道: > On Tuesday, December 3, 2013 6:45:42 AM UTC+5:30, iMath wrote: > > > so is there any way to create a temporary file by Python here ? > > > > http://docs.python.org/2/library/tempfile.html I use the following code to do the test ,but error occurred ,it prompts system cannot find specified files ,but the files are indeed exists there ,any help ? with tempfile.TemporaryFile() as fp: fp.write(("file '"+'a1.mp3'+"'\n").encode('utf-8')) fp.write(("file '"+'a2.mp3'+"'\n").encode('utf-8')) subprocess.call(['ffmpeg/ffmpeg', '-f', 'concat','-i',fp, '-c', 'copy', 'a3.mp3']) -- https://mail.python.org/mailman/listinfo/python-list
Re: how to implement a queue-like container with sort function
在 2013年12月4日星期三UTC+8上午7时23分49秒,Cameron Simpson写道: > On 03Dec2013 16:34, Ned Batchelder wrote: > > > On 12/3/13 4:19 PM, Cameron Simpson wrote: > > > >And then I check the source:-( He actually said "I want to a fixed > > > >length list-like container". That still sounds like a limit to the > > > >number of entries. > > > > > > Sorry, I was unclear. When I said, "I don't know where the idea came > > > from," I should have said, "the OP said he wanted a fixed-length > > > contained, but I don't know why he thinks that." > > > > Me either. > > > > Unless this is a homework task: "make one of these". > > -- > > Cameron Simpson > > > > It's as if all of Scottish cuisine is based on a dare. - Saturday Night Live deque meets my requirement here :) -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
在 2013年12月3日星期二UTC+8下午5时33分09秒,Alain Ketterlin写道: > Ben Finney writes: > > > > > Chris Angelico writes: > > > > > >> On Mon, Dec 2, 2013 at 10:34 PM, iMath wrote: > > >> > ffmpeg -f concat -i <(for f in ./*.wav; do echo "file '$f'"; done) -c > >> > copy output.wav > > >> > ffmpeg -f concat -i <(printf "file '%s'\n" ./*.wav) -c copy output.wav > > >> > ffmpeg -f concat -i <(find . -name '*.wav' -printf "file '%p'\n") -c > >> > copy output.wav > > >> > > >> In bash, the <(...) notation is like piping: it executes the command > > >> inside the parentheses and uses that as standard input to ffmpeg. > > > > > > Not standard input, no. What it does is create a temporary file to > > > contain the result, and inserts that file name on the command line. This > > > is good for programs that require an actual file, not standard input. > > > > Just in case (it may not be relevant to the current discussion): it may > > not be a file, it will more probably be a FIFO (i.e., not seekable). > > Here is the relevant part of the manual page: > > > > |Process Substitution > > |Process substitution is supported on systems that support named > > |pipes (FIFOs) or the /dev/fd method of naming open files. It > > |takes the form of <(list) or >(list). The process list is run > > |with its input or output connected to a FIFO or some file in > > |/dev/fd. The name of this file is passed as an argument to the > > |current command as the result of the expansion. > > > > -- Alain. thanks for your reply, but is there any method that we can convert this to python ? -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
在 2013年12月3日星期二UTC+8上午5时19分21秒,Ben Finney写道: > Chris Angelico writes: > > > > > On Mon, Dec 2, 2013 at 10:34 PM, iMath wrote: > > > > ffmpeg -f concat -i <(for f in ./*.wav; do echo "file '$f'"; done) -c > > > copy output.wav > > > > ffmpeg -f concat -i <(printf "file '%s'\n" ./*.wav) -c copy output.wav > > > > ffmpeg -f concat -i <(find . -name '*.wav' -printf "file '%p'\n") -c copy > > > output.wav > > > > > > In bash, the <(...) notation is like piping: it executes the command > > > inside the parentheses and uses that as standard input to ffmpeg. > > > > Not standard input, no. What it does is create a temporary file to > > contain the result, and inserts that file name on the command line. This > > is good for programs that require an actual file, not standard input. > > > > So the above usage seems right to me: the ‘ffmpeg -i FOO’ option is > > provided with a filename dynamically created by Bash, referring to a > > temporary file that contains the output of the subshell. > > > > -- > > \ “Welchen Teil von ‘Gestalt’ verstehen Sie nicht? [What part of | > > `\‘gestalt’ don't you understand?]” —Karsten M. Self | > > _o__) | > > Ben Finney so is there any way to create a temporary file by Python here ? -- https://mail.python.org/mailman/listinfo/python-list
Re: how to implement a queue-like container with sort function
在 2013年11月29日星期五UTC+8下午10时57分36秒,Mark Lawrence写道: > On 29/11/2013 12:33, iMath wrote: > > > > > > BTW ,the Queue object has an attribute 'queue' ,but I cannot find it > > described in the DOC ,what it means ? > > > > > > > Really? AttributeError: type object 'Queue' has no attribute 'queue' > > > > -- > > Python is the second best programming language in the world. > > But the best has yet to be invented. Christian Tismer > > > > Mark Lawrence you can do a check by hasattr() -- https://mail.python.org/mailman/listinfo/python-list
using ffmpeg command line with python's subprocess module
I have few wav files that I can use either of the following command line mentioned here https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20%28join,%20merge%29%20media%20files to concatenate ffmpeg -f concat -i <(for f in ./*.wav; do echo "file '$f'"; done) -c copy output.wav ffmpeg -f concat -i <(printf "file '%s'\n" ./*.wav) -c copy output.wav ffmpeg -f concat -i <(find . -name '*.wav' -printf "file '%p'\n") -c copy output.wav anyone know how to convert either of them to work with python's subprocess module, it would be better if your solution is platform independent . -- https://mail.python.org/mailman/listinfo/python-list
Re: how to implement a queue-like container with sort function
it seems PriorityQueue satisfy my requirement here . BTW ,the Queue object has an attribute 'queue' ,but I cannot find it described in the DOC ,what it means ? -- https://mail.python.org/mailman/listinfo/python-list
Re: how to implement a queue-like container with sort function
hey , you used >>> sorted(a.queue) this means the queue.Queue() has an attribute queue ,but I cannot find it described in the DOC ,where you find it ? -- https://mail.python.org/mailman/listinfo/python-list
Re: how to implement a queue-like container with sort function
All in all,I want to first fill the container, then sort it and process all the contents in it -- https://mail.python.org/mailman/listinfo/python-list
how to implement a queue-like container with sort function
I want to a fixed length list-like container, it should have a sorted()-like function that I can use to sort it,I think there should also a function I can use it to detect whether the numbers of items in it reaches the length of the container , because if the numbers of items in it reaches the length(fixed) of the container,I want to process the data in it .Is there a container in Python like this ?If not, what base container should be used to implement such container? the container is similar to queue ,but queue doesn't have a sort function -- https://mail.python.org/mailman/listinfo/python-list
Re: run command line on Windows without showing DOS console window
在 2013年11月20日星期三UTC+8下午10时49分50秒,Tim Golden写道: > On 20/11/2013 14:44, iMath wrote: > > > > > > > > > is there anyway to run command line on Windows without showing DOS console > > window ? > > > > > > can you use the following command line to give a little example ? > > > > > > wget -r -np -nd http://example.com/packages/ > > > > > > the path to wget is C:\Program Files\GnuWin32\bin\wget.exe > > > > > > > subprocess.call(["wget", "-r", "-np", "-nd", "http://example.com";]) > > > > TJG Have you tried it ? the DOS console window still pops up? but I found when shell=True ,the DOS console window doesn't pop up,anyone can explain why ? -- https://mail.python.org/mailman/listinfo/python-list
run command line on Windows without showing DOS console window
is there anyway to run command line on Windows without showing DOS console window ? can you use the following command line to give a little example ? wget -r -np -nd http://example.com/packages/ the path to wget is C:\Program Files\GnuWin32\bin\wget.exe -- https://mail.python.org/mailman/listinfo/python-list
Re: pywin32 programming error on Win7 with shell.SHGetDesktopFolder, desktop.BindToObject, desktop.GetDisplayNameOf
I solved it like the following from win32com.shell import shell, shellcon import os def launch_file_explorer(path, files): ''' Given a absolute base path and names of its children (no path), open up one File Explorer window with all the child files selected ''' folder_pidl = shell.SHILCreateFromPath(path,0)[0] desktop = shell.SHGetDesktopFolder() shell_folder = desktop.BindToObject(folder_pidl, None,shell.IID_IShellFolder) name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, shellcon.SHGDN_FORPARSING|shellcon.SHGDN_INFOLDER), item) for item in shell_folder]) print(name_to_item_mapping) to_show = [] for file in files: if file in name_to_item_mapping: to_show.append(name_to_item_mapping[file]) # else: # raise Exception('File: "%s" not found in "%s"' % (file, path)) shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 0) p=r'E:\aa' print(os.listdir(p)) launch_file_explorer(p, os.listdir(p)) -- https://mail.python.org/mailman/listinfo/python-list
Re: pywin32 programming error on Win7 with shell.SHGetDesktopFolder, desktop.BindToObject, desktop.GetDisplayNameOf
I solved it like the following from win32com.shell import shell, shellcon import os def launch_file_explorer(path, files): ''' Given a absolute base path and names of its children (no path), open up one File Explorer window with all the child files selected ''' folder_pidl = shell.SHILCreateFromPath(path,0)[0] desktop = shell.SHGetDesktopFolder() shell_folder = desktop.BindToObject(folder_pidl, None,shell.IID_IShellFolder) name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, shellcon.SHGDN_FORPARSING|shellcon.SHGDN_INFOLDER), item) for item in shell_folder]) print(name_to_item_mapping) to_show = [] for file in files: if file in name_to_item_mapping: to_show.append(name_to_item_mapping[file]) # else: # raise Exception('File: "%s" not found in "%s"' % (file, path)) shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 0) p=r'E:\aa' print(os.listdir(p)) launch_file_explorer(p, os.listdir(p)) -- https://mail.python.org/mailman/listinfo/python-list
Re: pywin32 programming error on Win7 with shell.SHGetDesktopFolder, desktop.BindToObject, desktop.GetDisplayNameOf
thanks, I found out the reason: this question has no relationship with Win7 or WinXP,but related to the users' system setting . GetDisplayNameOf() only gives the DISPLAY name ,so the filename with or without extension acording to whether the user want to view files in the explorer with extension . my settings is that filename with extension on WinXP but not on Win7,while os.listdir() returns filenames with extension on both of them ,this caused my problem here . so anyone know how to fix my problem ? I mainly want to use shell.SHOpenFolderAndSelectItems() here. -- https://mail.python.org/mailman/listinfo/python-list
Re: pywin32 programming error on Win7 with shell.SHGetDesktopFolder, desktop.BindToObject, desktop.GetDisplayNameOf
在 2013年11月8日星期五UTC+8下午5时47分43秒,Tim Golden写道: > On 08/11/2013 03:30, iMath wrote: > > > > > > When running the following code on WinXP , all is fine , > > > -- > > > from win32com.shell import shell > > > > > > def launch_file_explorer(path, files): > > > > > > folder_pidl = shell.SHILCreateFromPath(path,0)[0] > > > desktop = shell.SHGetDesktopFolder() > > > shell_folder = desktop.BindToObject(folder_pidl, > > None,shell.IID_IShellFolder) > > > name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, 0), item) > > for item in shell_folder]) > > > to_show = [] > > > for file in files: > > > if file not in name_to_item_mapping: > > > raise Exception('File: "{}" not found in "{}"'.format(file, > > path)) > > > to_show.append(name_to_item_mapping[file]) > > > shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 0) > > > import os > > > > > > > > > p=r'E:\aa' > > > print(os.listdir(p)) > > > launch_file_explorer(p, os.listdir(p)) > > > > > > Did you mean to call .GetDisplayNameOf against the desktop folder? I > > would have thought you wanted shell_folder.GetDisplayNameOf(item, 0). > > > > TJG I mainly want to use shell.SHOpenFolderAndSelectItems() -- https://mail.python.org/mailman/listinfo/python-list
Re: pywin32 programming error on Win7 with shell.SHGetDesktopFolder, desktop.BindToObject, desktop.GetDisplayNameOf
在 2013年11月8日星期五UTC+8下午5时47分43秒,Tim Golden写道: > On 08/11/2013 03:30, iMath wrote: > > > > > > When running the following code on WinXP , all is fine , > > > -- > > > from win32com.shell import shell > > > > > > def launch_file_explorer(path, files): > > > > > > folder_pidl = shell.SHILCreateFromPath(path,0)[0] > > > desktop = shell.SHGetDesktopFolder() > > > shell_folder = desktop.BindToObject(folder_pidl, > > None,shell.IID_IShellFolder) > > > name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, 0), item) > > for item in shell_folder]) > > > to_show = [] > > > for file in files: > > > if file not in name_to_item_mapping: > > > raise Exception('File: "{}" not found in "{}"'.format(file, > > path)) > > > to_show.append(name_to_item_mapping[file]) > > > shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 0) > > > import os > > > > > > > > > p=r'E:\aa' > > > print(os.listdir(p)) > > > launch_file_explorer(p, os.listdir(p)) > > > > > > Did you mean to call .GetDisplayNameOf against the desktop folder? I > > would have thought you wanted shell_folder.GetDisplayNameOf(item, 0). > > > > TJG I mainly want to use shell.SHOpenFolderAndSelectItems() -- https://mail.python.org/mailman/listinfo/python-list
pywin32 programming error on Win7 with shell.SHGetDesktopFolder, desktop.BindToObject, desktop.GetDisplayNameOf
When running the following code on WinXP , all is fine , -- from win32com.shell import shell def launch_file_explorer(path, files): folder_pidl = shell.SHILCreateFromPath(path,0)[0] desktop = shell.SHGetDesktopFolder() shell_folder = desktop.BindToObject(folder_pidl, None,shell.IID_IShellFolder) name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, 0), item) for item in shell_folder]) to_show = [] for file in files: if file not in name_to_item_mapping: raise Exception('File: "{}" not found in "{}"'.format(file, path)) to_show.append(name_to_item_mapping[file]) shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 0) import os p=r'E:\aa' print(os.listdir(p)) launch_file_explorer(p, os.listdir(p)) -- however ,when tested on Win7,I got the following error -- ['b1', 'b2', 't.txt'] Traceback (most recent call last): File "D:\g.py", line 21, in launch_file_explorer(p, os.listdir(p)) File "D:\g.py", line 13, in launch_file_explorer raise Exception('File: "{}" not found in "{}"'.format(file, path)) Exception: File: "t.txt" not found in "E:\aa" -- I nearly have no experience on pywin32 programming ,the above code is googled,anyone can help me fix this error ?thanks in advance ! -- https://mail.python.org/mailman/listinfo/python-list
Resuming the HTTP Download of a File and HTTP compression
the file I want to download is 100 bytes uncompressed, the downloads was interrupted when 5000 bytes compressed data was transmitted .If I want to Resuming the HTTP Download ,I wonder what value of the HTTP Range header should be ,“bytes=5000-“ or “bytes= -”? why ? -- http://mail.python.org/mailman/listinfo/python-list
Resuming the HTTP Download of a File and HTTP compression
the file I want to download is 100 bytes uncompressed, the downloads was interrupted when 5000 bytes compressed data was transmitted .If I want to Resuming the HTTP Download ,I wonder what value of the HTTP Range header should be ,“bytes=5000-“ or “bytes= -”? why ? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
在 2012年12月24日星期一UTC+8上午8时34分47秒,iMath写道: > how to detect the character encoding in a web page ? > > such as this page > > > > http://python.org/ here is one thread that can help me understanding my code http://stackoverflow.com/questions/17001407/how-to-detect-the-character-encoding-of-a-web-page-programmatically/17009285#17009285 -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
在 2012年12月24日星期一UTC+8上午8时34分47秒,iMath写道: > how to detect the character encoding in a web page ? > > such as this page > > > > http://python.org/ Finally ,I found by using PyQt’s QtextStream , QTextCodec and chardet ,we can get a web page code more securely even for this bad page http://www.qnwz.cn/html/yinlegushihui/magazine/2013/0524/425731.html this script http://www.flvxz.com/getFlv.php?url=aHR0cDojI3d3dy41Ni5jb20vdTk1L3ZfT1RFM05UYzBNakEuaHRtbA== and this page without chardet in its source code http://msdn.microsoft.com/en-us/library/bb802962(v=office.12).aspx from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtNetwork import * import sys import chardet def slotSourceDownloaded(reply): redirctLocation=reply.header(QNetworkRequest.LocationHeader) redirctLocationUrl=reply.url() if not redirctLocation else redirctLocation #print(redirctLocationUrl,reply.header(QNetworkRequest.ContentTypeHeader)) if (reply.error()!= QNetworkReply.NoError): print('', reply.errorString()) return pageCode=reply.readAll() charCodecInfo=chardet.detect(pageCode.data()) textStream=QTextStream(pageCode) codec=QTextCodec.codecForHtml(pageCode,QTextCodec.codecForName(charCodecInfo['encoding'] )) textStream.setCodec(codec) content=textStream.readAll() print(content) if content=='': print('-', 'cannot find any resource !') return reply.deleteLater() qApp.quit() if __name__ == '__main__': app =QCoreApplication(sys.argv) manager=QNetworkAccessManager () url =input('input url :') request=QNetworkRequest (QUrl.fromEncoded(QUrl.fromUserInput(url).toEncoded())) request.setRawHeader("User-Agent" ,'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17 SE 2.X MetaSr 1.0') manager.get(request) manager.finished.connect(slotSourceDownloaded) sys.exit(app.exec_()) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
在 2012年12月24日星期一UTC+8上午8时34分47秒,iMath写道: > how to detect the character encoding in a web page ? > > such as this page > > > > http://python.org/ by the way ,we cannot get character encoding programmatically from the mate data without knowing the character encoding ahead ! -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
在 2012年12月24日星期一UTC+8上午8时34分47秒,iMath写道: > how to detect the character encoding in a web page ? > > such as this page > > > > http://python.org/ I found PyQt’s QtextStream can very accurately detect the character encoding in a web page . even for this bad page http://www.qnwz.cn/html/yinlegushihui/magazine/2013/0524/425731.html chardet and beautiful soup failed ,but QtextStream can get the right result . here is my code from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtNetwork import * import sys def slotSourceDownloaded(reply): redirctLocation=reply.header(QNetworkRequest.LocationHeader) redirctLocationUrl=reply.url() if not redirctLocation else redirctLocation print(redirctLocationUrl) if (reply.error()!= QNetworkReply.NoError): print('', reply.errorString()) return content=QTextStream(reply).readAll() if content=='': print('-', 'cannot find any resource !') return print(content) reply.deleteLater() qApp.quit() if __name__ == '__main__': app =QCoreApplication(sys.argv) manager=QNetworkAccessManager () url =input('input url :') request=QNetworkRequest (QUrl.fromEncoded(QUrl.fromUserInput(url).toEncoded())) request.setRawHeader("User-Agent" ,'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17 SE 2.X MetaSr 1.0') manager.get(request) manager.finished.connect(slotSourceDownloaded) sys.exit(app.exec_()) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
在 2012年12月24日星期一UTC+8上午8时34分47秒,iMath写道: > how to detect the character encoding in a web page ? > > such as this page > > > > http://python.org/ I found PyQt’s QtextStream can very accurately detect the character encoding in a web page . even for this bad page chardet and beautiful soup failed ,but QtextStream can get the right result . here is my code from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtNetwork import * import sys def slotSourceDownloaded(reply): redirctLocation=reply.header(QNetworkRequest.LocationHeader) redirctLocationUrl=reply.url() if not redirctLocation else redirctLocation print(redirctLocationUrl) if (reply.error()!= QNetworkReply.NoError): print('', reply.errorString()) return content=QTextStream(reply).readAll() if content=='': print('-', 'cannot find any resource !') return print(content) reply.deleteLater() qApp.quit() if __name__ == '__main__': app =QCoreApplication(sys.argv) manager=QNetworkAccessManager () url =input('input url :') request=QNetworkRequest (QUrl.fromEncoded(QUrl.fromUserInput(url).toEncoded())) request.setRawHeader("User-Agent" ,'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17 SE 2.X MetaSr 1.0') manager.get(request) manager.finished.connect(slotSourceDownloaded) sys.exit(app.exec_()) -- http://mail.python.org/mailman/listinfo/python-list
use python to split a video file into a set of parts
I use the following python code to split a FLV video file into a set of parts ,when finished ,only the first part video can be played ,the other parts are corrupted.I wonder why and Is there some correct ways to split video files import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy print(chunksize , type(chunksize )) def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir)# make dir, read/write parts else: for fname in os.listdir(todir):# delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while True:# eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum += 1 filename = os.path.join(todir, ('part{}.flv'.format(partnum))) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close()# or simply open().write() input.close() assert partnum <= # join sort fails if 5 digits return partnum if __name__ == '__main__': fromfile = input('File to be split: ') # input if clicked todir= input('Directory to store part files:') print('Splitting', fromfile, 'to', todir, 'by', chunksize) parts = split(fromfile, todir, chunksize) print('Split finished:', parts, 'parts are in', todir) -- http://mail.python.org/mailman/listinfo/python-list
python : how to Opens folder with specified items selected on Windows
I want to Opens folder with specified items selected on Windows ,I looked up the The Windows Shell Reference found a function fit for this job SHOpenFolderAndSelectItems http://msdn.microsoft.com/en-us/library/windows/desktop/bb762232(v=vs.85).aspx but I cannot find an example on how to use it with python so anyone can give a little example ? I have another extra requirement :if that folder already open ,don??t open it again ,just activate it and selected the file-- http://mail.python.org/mailman/listinfo/python-list
Re: executor.map() TypeError: zip argument #2 must support iteration
在 2013年4月1日星期一UTC+8下午3时48分34秒,Steven D'Aprano写道: > On Sun, 31 Mar 2013 21:45:21 -0700, iMath wrote: > > > > > executor.map()TypeError: zip argument #2 must support iteration > > > > > > when I run it ,just generated TypeError: zip argument #2 must support > > > iteration. can anyone help me fix this problem ? > > > > Yes. Read the error message, and inspect the line that is in error. You > > have: > > > > > future_to_url = executor.map(str,lst100, 60) > > > > executor.map has three arguments: > > > > Arg 0: str > > Arg 1: list of 100 ints > > Arg 2: int 60 > > > > Argument 2, the number 60, does not support iteration, since it is an int. > > > > Now read the docs for map. At the interactive interpreter, do this: > > > > py> from concurrent.futures import ThreadPoolExecutor > > py> help(ThreadPoolExecutor.map) > > > > > > and you will see the following documentation: > > > > map(self, fn, *iterables, timeout=None) > > Returns a iterator equivalent to map(fn, iter). > > > > Args: > > fn: A callable that will take take as many arguments as there are > > passed iterables. > > timeout: The maximum number of seconds to wait. If None, then > > there is no limit on the wait time. > > > > > > Notice that the iterables argument is prefixed with * symbol. That means > > that it collects all the remaining positional arguments, which means that > > the timeout argument is keyword only. > > > > So try this: > > > > > > future_to_url = executor.map(str, lst100, timeout=60) > > > > > > -- > > Steven thanks for clarification.I thought argument 2 is lst100 -- http://mail.python.org/mailman/listinfo/python-list
executor.map() TypeError: zip argument #2 must support iteration
executor.map()TypeError: zip argument #2 must support iteration when I run it ,just generated TypeError: zip argument #2 must support iteration. can anyone help me fix this problem ? import time, concurrent.futures lst100=[i for i in range(100)] t1=time.clock() print(list(map(str,lst100))) t2=time.clock() print(t2-t1) t3=time.clock() with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor: future_to_url = executor.map(str,lst100, 60) print(list(future_to_url)) t4=time.clock() print(t4-t3) -- http://mail.python.org/mailman/listinfo/python-list
changes on windows registry doesnât take effect immediately
changes on windows registry doesnât take effect immediately I am trying to change IEâs proxy settings by the following 2 code snippets to enable the proxy by this code from winreg import * with OpenKey(HKEY_CURRENT_USER,r"Software\Microsoft\Windows\CurrentVersion\Internet Settings" ,0, KEY_ALL_ACCESS) as key: SetValueEx(key,"ProxyServer",0, REG_SZ, "127.0.0.1:8087") SetValueEx(key,"ProxyEnable",0, REG_DWORD, 1) SetValueEx(key,"ProxyOverride",0, REG_SZ, "") FlushKey(key) to disable the proxy by this code from winreg import * with OpenKey(HKEY_CURRENT_USER,r"Software\Microsoft\Windows\CurrentVersion\Internet Settings" ,0, KEY_ALL_ACCESS) as key: DeleteValue(key,"ProxyServer") SetValueEx(key,"ProxyEnable",0, REG_DWORD, 0) DeleteValue(key,"ProxyOverride") FlushKey(key) but the changes on windows registry doesnât take effect immediately,so is there some way to change the windows registry and let the changes take effect immediately without restarting IE ? BTW ,I use the code on winxp ,and I am going to embed the 2 code snippets in my PyQt application . -- http://mail.python.org/mailman/listinfo/python-list
read and write the same text file
read and write the same text file Open a text file ,read the content ,then make some change on it ,then write it back to the file ,now the modified text should only has the modified content but not the initial content ,so can we implement this by only set the mode parameter with open() function ?if yes ,what the parameter should be ?if no ,can we implement this by only one with statement ? I implement this with 2 with statement as the following replace_pattern = re.compile(r"<.+?>",re.DOTALL) def text_process(file): with open(file,'r') as f: text = f.read() with open(file,'w') as f: f.write(replace_pattern.sub('',text)) -- http://mail.python.org/mailman/listinfo/python-list
which situations should we use thread. join() ?
which situations should we use thread. join() ? http://bpaste.net/show/yBDGfrlU7BDDpvEZEHmo/ why do we not put thread. join() in this code ? -- http://mail.python.org/mailman/listinfo/python-list
each process only has one main thread ,right ?
When a program starts up, one thread begins running immediately. This is usually called the main thread of the program ,so each process only has one main thread ,right ? -- http://mail.python.org/mailman/listinfo/python-list
how to change system-wide proxy settings by Python ?
I have already known a valid proxy server(63.141.216.159)and port(8087) which support both http and https protocols ,so how to change system-wide proxy settings to this proxy by Python ? I use WinXP ,can you show me an example of this ? thanks in advance ! -- http://mail.python.org/mailman/listinfo/python-list
Re: [os.path.join(r'E:\Python', name) for name in []] returns []
在 2013年1月29日星期二UTC+8下午9时33分26秒,Steven D'Aprano写道: > iMath wrote: > why [os.path.join(r'E:\Python', name) for name in []] returns > [] ? Because you are iterating over an empty list, []. That list > comprehension is the equivalent of: result = [] for name in []: > result.append( os.path.join(r'E:\Python', name) ) Since you iterate over an > empty list, the body of the loop never executes, and the result list remains > empty. What did you expect it to do? -- Steven just in order to get the full path name of each file . -- http://mail.python.org/mailman/listinfo/python-list
[os.path.join(r'E:\Python', name) for name in []] returns []
why [os.path.join(r'E:\Python', name) for name in []] returns [] ? please explain it in detail ! -- http://mail.python.org/mailman/listinfo/python-list
what is the difference between commenting and uncommenting the __init__ method in this class?
what is the difference between commenting and uncommenting the __init__ method in this class? class CounterList(list): counter = 0 ##def __init__(self, *args): ##super(CounterList, self).__init__(*args) def __getitem__(self, index): self.__class__.counter += 1 return super(CounterList, self).__getitem__(index) -- http://mail.python.org/mailman/listinfo/python-list
anyone can make a Python bindings of VLC-Qt ?
anyone can make a Python bindings of VLC-Qt ? https://github.com/ntadej/vlc-qt accurately, can anyone make a PyQt bindings of VLC-Qt ? -- http://mail.python.org/mailman/listinfo/python-list
Re: To make a method or attribute private
在 2013年1月17日星期四UTC+8上午8时34分22秒,iMath写道: > To make a method or attribute private (inaccessible from the outside), simply > start its > name with two underscores > > > 《Beginning Python From Novice to Professional》 > > > but there is another saying goes: > Beginning a variable name with a single underscore indicates that the > variable should be treated as ‘private’. > > > I test both these 2 rules ,it seems only names that start with two > underscores are REAL private methods or attributes . > > > >>> class A: > ... def __init__(self): > ... self.a = 'a' > ... self._a = '_a' > ... self.__a = '__a' > ... > > > > > > > >>> ap = A() > >>> ap.a > 'a' > >>> ap._a > '_a' > >>> ap.__a > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: A instance has no attribute '__a' > > > so what is your opinion about single leading underscore and private methods > or attributes? so there is no REAL private variable in Python but conversion exists in it that python programmer should follow and recognize .right ? -- http://mail.python.org/mailman/listinfo/python-list
Re: To make a method or attribute private
在 2013年1月17日星期四UTC+8上午9时04分00秒,alex23写道: > On Jan 17, 10:34 am, "iMath" <2281570...@qq.com> wrote: > > > To make a method or attribute private (inaccessible from the outside), > > simply start its > > > name with two underscores > > > > > > but there is another saying goes: > > > Beginning a variable name with a single underscore indicates that the > > variable should be treated as ‘private’. > > > I test both these 2 rules ,it seems only names that start with two > > underscores are REAL private methods or attributes . > > > so what is your opinion about single leading underscore and private methods > > or attributes? > > > > The key word in the second quote is "indicates". Placing a single > > underscore before an attribute name does nothing but _show_ other > > programmers that you consider this to be part of the implementation > > rather than the interface, and that you make no guarantees of its > > continued existence over time. > > > > More importantly, however: there is no real concept of "private" > > attributes in Python. Try this at the command prompt: > > > > >>> ap._A__a > > '__a' > > > > It's still readable, and it's still writable too. The double- > > underscore naming is referred to as "name mangling" and while it's > > often passed off as the way to make private methods in Python (the > > tutorial even states this), what it is really intended for is to > > ensure that multiple inheritance works correctly: > > > > >>> class A(object): > > ... foo = 'A' > > ... def get_A_foo(self): > > ... return self.foo > > ... > > >>> class B(object): > > ... foo = 'B' > > ... def get_B_foo(self): > > ... return self.foo > > ... > > >>> class C(A, B): > > ... def __init__(self): > > ... super(C, self).__init__() > > ... > > >>> c = C() > > >>> c.get_A_foo() > > 'A' > > >>> c.get_B_foo() > > 'A' > > > > Here, we haven't mangled the attribute 'foo' on either A or B, so on > > the instance of C, which inherits from both, the inherited methods are > > referring to the same attribute, which is A's in this case due to the > > method resolution order. By re-naming 'foo' on both A and B to > > '__foo', each can then refer to their _own_ attribute, and also allow > > for C to have its own 'foo' attribute which doesn't conflict with > > either of them: > > > > >>> class A(object): > > ... __foo = 'A' > > ... def get_A_foo(self): > > ... return self.__foo > > ... > > >>> class B(object): > > ... __foo = 'B' > > ... def get_B_foo(self): > > ... return self.__foo > > ... > > >>> class C(A, B): > > ... foo = 'C' > > ... def __init__(self): > > ... super(C, self).__init__() > > ... > > >>> c = C() > > >>> c.get_A_foo() > > 'A' > > >>> c.get_B_foo() > > 'B' > > >>> c.foo > > 'C' > > > > There is no way to make an externally private attribute. This is > > generally considered a good thing by most Python developers: if I > > _need_ to access your class's implementation, I can do so, but the > > name mangling forces me to be aware that this is something you don't > > recommend doing. You'll often hear the term "consenting adults" used > > to refer to this, meaning we can all decide for ourselves if we're > > willing to risk using an implementation detail. what's the meaning of 'object' in class A(object) and class B(object) ? -- http://mail.python.org/mailman/listinfo/python-list
To make a method or attribute private
To make a method or attribute private (inaccessible from the outside), simply start its name with two underscores 《Beginning Python From Novice to Professional》 but there is another saying goes: Beginning a variable name with a single underscore indicates that the variable should be treated as ‘private’. I test both these 2 rules ,it seems only names that start with two underscores are REAL private methods or attributes . >>> class A: ... def __init__(self): ... self.a = 'a' ... self._a = '_a' ... self.__a = '__a' ... >>> ap = A() >>> ap.a 'a' >>> ap._a '_a' >>> ap.__a Traceback (most recent call last): File "", line 1, in ? AttributeError: A instance has no attribute '__a' so what is your opinion about single leading underscore and private methods or attributes? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to implement mouse gesture by python or pyqt ?
在 2013年1月10日星期四UTC+8上午8时06分13秒,Michael Torrie写道: > On 01/08/2013 07:57 PM, iMath wrote: > > > 在 2013年1月8日星期二UTC+8上午8时44分20秒,iMath写道: > > >> It would be better to give me some examples .thanks in advance ! > > >> > > >> > > >> > > >> P.S. which module or lib are needed ? > > > > > > what I wanna perhaps like this: when a right mouse button is pressed > > > and we go down and right with a cursor. As in letter 'L'. Our mouse > > > gesture will close the window. I googled such gesture examples on > > > PyQt4 ,but hard to find one ,so your help will be greatly appreciated > > > ! thanks inadvance ! > > > > My guess is that if you google for it you'll find a gesture recognition > > module for python. moosegesture.py is one such implementation. However > > it is up to you to tie it into your chosen GUI toolkit. It merely > > processes tuples of points in the gesture. Each GUI toolkit has mailing > > lists and forums that would help you know that information, which is not > > really python-specific. oh yes ,I find it moosegesture.py -- http://mail.python.org/mailman/listinfo/python-list
How to call wget by python ?
can you give me an example code ? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to download internet files by python ?
在 2013年1月8日星期二UTC+8下午1时04分54秒,Roy Smith写道: > In article , > > Cameron Simpson wrote: > > > > > On 07Jan2013 20:19, iMath wrote: > > > | for example ,if I want to download this file ,how to implement the > > download > > > | functionality by python ? > > > | > > > | http://down.51voa.com/201208/se-ed-foreign-students-friends-16aug12.mp3 > > > | > > > | as for download speed ,of course ,the fast ,the better ,so how to > > > | implement it ? > > > | It would be better to show me an example :) thanks !!! > > > > > > Look at urllib2. > > > > Even better, look at requests > > (http://docs.python-requests.org/en/latest/). There's nothing you can > > do with requests that you can't do with urllib2, but the interface is a > > whole lot easier to work with. There is also a httplib2 module https://code.google.com/p/httplib2/ which one is more pythonic and powerful ? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get the selected text of the webpage in chrome through python ?
在 2013年1月9日星期三UTC+8下午5时35分15秒,Alister写道: > On Mon, 07 Jan 2013 20:20:28 -0800, iMath wrote: > > > > > How to get the selected text of the webpage in chrome through python ? > > > > i think you need to explain your requirement further > > also what do you want to do to the text once you have it? > > > > > > > > > > -- > > Genius is one percent inspiration and ninety-nine percent perspiration. > > -- Thomas Alva Edison I want to google it with a mouse gesture -- http://mail.python.org/mailman/listinfo/python-list
Re: How to implement mouse gesture by python or pyqt ?
在 2013年1月8日星期二UTC+8上午8时44分20秒,iMath写道: > It would be better to give me some examples .thanks in advance ! > > > > P.S. which module or lib are needed ? what I wanna perhaps like this: when a right mouse button is pressed and we go down and right with a cursor. As in letter 'L'. Our mouse gesture will close the window. I googled such gesture examples on PyQt4 ,but hard to find one ,so your help will be greatly appreciated ! thanks inadvance ! -- http://mail.python.org/mailman/listinfo/python-list