2018年4月30日 星期一

[ Python 常見問題 ] Converting Epoch time into the datetime

Source From Here 
Question 
I am getting a response from the rest is an Epoch time format like: 
  1. start_time = 1234566  
  2. end_time = 1234578  
I want to convert that epoch seconds to be transformed into below format (Check strftime): 
2012-09-12 21:00:00

How-To 
To convert your time value (float or int) to a formatted string, use: 
>>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370)) // For my local TimeZone as UTC+8 
'2012-09-13 14:22:50' 

>>> time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1347517370)) // The time with TimeZone as UTC+0 
'2012-09-13 06:22:50'

Reference: 
* time.localtime([secs]): 
Like gmtime() but converts to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.


[ Python 常見問題 ] How can I check for Python version in a program that uses new language features?

Source From Here 
Question 
If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script? 

How do I get control early enough to issue an error message and exit? 

For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python. 

I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program: 
  1. import sys  
  2. if sys.version_info < (24):  
  3.     raise "must use python 2.5 or greater"  
  4. else:  
  5.     # syntax error in 2.4, ok in 2.5  
  6.     x = 1 if True else 2  
  7.     print x  
When run under 2.4, I want this result 
$ ~/bin/python2.4 tern.py 
must use python 2.5 or greater

and not this result: 
~/bin/python2.4 tern.py 
File "tern.py", line 5
x = 1 if True else 2
^
SyntaxError: invalid syntax

How-To 
You can test using eval
  1. try:  
  2.   eval("1 if True else 2")  
  3. except SyntaxError:  
  4.   # doesn't have ternary  
Also, with is available in Python 2.5, just add from __future__ import with_statement. To get control early enough, you could split it into different .py files and check compatibility in the main file before importing (e.g. in__init__.py in a package)

[ Python 常見問題 ] How can I find all matches to a regular expression in Python?

Source From Here 
Question 
In a program I'm writing I have Python use the re.search() function to find matches in a block of text and print the results. However, the program exits once it finds the first match in the block of text. How do I do this repeatedly where the program doesn't stop until ALL matches have been found? Is there a separate function to do this? 

How-To 
Use re.findall or re.finditer instead: 
* re.findall(pattern, string) returns a list of matching strings. 
* re.finditer(pattern, string) returns an iterator over MatchObject objects.

One simple example: 
  1. import re  
  2.   
  3. text = r'''My name is John. His name is Peter.  
  4. Today is sunny and we all want to go outside for picnic.'''  
  5.   
  6. for e in re.findall('is ([a-zA-Z]+)', text):  
  7.     print('Found "{}"'.format(e))  
Output: 
Found "John" 
Found "name" 
Found "Peter" 
Found "sunny"


[ Python 文章收集 ] Dynamic Attributes in Python

Source From Here 
Preface 
One of the strengths of a dynamic language is that it allows you to more easily work introspection and light weight meta-programming into your every day code. In Python, one of the primary ways of taking advantage of the dynamic nature of the language is through attribute access. 
Note: this is part one in a series of posts about basic Python functionality. 

In most cases, to get an attribute of an object, you just want to use obj.field. But if you don’t know the name of the field until runtime, you can use getattr(obj, 'field'): 
  1. def print_field(obj, field):  
  2.     try:  
  3.         print getattr(obj, field)  
  4.     except AttributeError:  
  5.         print 'No %s field' % field  
This is a fairly common pattern, so you can avoid the extra try/catch and use the third default parameter: 
  1. def print_field(obj, field):  
  2.     print getattr(obj, field, 'No %s field' % field)  
Both attribute access methods are virtually identical in terms of performance. The regular method produces slightly cleaner code, so normally you would use that. Besides, when do you NOT know the names of the fields you want to access ahead of time? 

More 
If you’re dealing with data, you don’t always know. For example, say you’re mapping URLs to view methods. If the user hits /user/123/settings, you could route that to a view function as follows: 
  1. class ViewClass(object):  
  2.   
  3.     def route(request):  
  4.         return getattr(self, request.url.split('/')[-1], 'not_found_404')(request)  
  5.   
  6.     def settings(request):  
  7.         return HttpResponse('Here is your settings page!')  
  8.   
  9.     def not_found_404(request):  
  10.         return HttpResponse('404 Page Not Found', code=404)  
Of course, you could always do this with a pre-defined set of URLs, but the point is that you have a built-in way to avoid that code duplication. In general, this is known as keeping your code DRY. For example, notice the duplication of tokens in code like the following: 
  1. obj.first_name.first_child.value = 'Chase'  
  2. obj.last_name.first_child.value = 'Seibert'  
  3. obj.phone.first_child.value = '(555) 123-4567'  
Instead, you could do something like the following: 
  1. for (field, value) in (('first_name', 'Chase'), ('last_name', 'Seibert'), ('phone', '(555) 123-4567')):  
  2.     getattr(obj, field).first_child.value = value  
While this is certainly more code, for a larger number of lines, there will be a code savings. It’s also easy to refactor all the obj.field lines at once, if for example you need to change it to obj.field.set(value). You can also make use of dynamic attributes on the class side by over-riding __getattr__. 
  1. class Counter(object):  
  2.     def __getattr__(self, name):  
  3.         ''' will only get called for undefined attributes '''  
  4.         setattr(self, name) = 0  
  5.   
  6. counter = Counter()  
  7. counter.foo = counter.foo + 100  
  8. print counter.foo  # prints '100'  
There is an alternate magic method called __getattribute__ that fires even for attributes that are already declared. But be careful, it’s easy to get into an infinite recursion loop here. 
  1. class Logger(object):  
  2.     def __init__(self):  
  3.         print('Initialized Logger...')  
  4.         # self.foobar = 100  
  5.   
  6.     def __getattribute__(self, name):  
  7.         print('Accessed attribute {}'.format(name))  
  8.         return object.__getattribute__(self, name)  
  9.   
  10. logger = Logger()  
  11. logger.foobar = 10  
  12. print("logger.foobar = {}".format(logger.foobar))  
Output: 
Initialized Logger... 
Accessed attribute foobar 
logger.foobar = 10

This is a trivial example, better implemented with decorators. But that is a subject for another post! 

Finally, there is a sister to getattr called setattr. As you would expect, this will set attributes by name. Here is a quick example: 
  1. class MyModel(object):  
  2.   
  3.     @classmethod  
  4.     def from_kwargs(cls, **kwargs):  
  5.         obj = cls()  
  6.         for (field, value) in kwargs.items():  
  7.             setattr(self, field, value)  
  8.         return obj  
  9.   
  10. model = MyModel.from_kwargs(foo=1, bar=2)  
  11. print model.foo, model.bar  # prints '1, 2'  


[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...