1. 程式人生 > >Learning Python

Learning Python

---------------------------------------------------------------------------------------------

解決迴圈引用:

1. 不要import,直接將物件(動態)傳過去,直接呼叫物件的方法;

    (適合只有兩層迴圈呼叫:A->B, B->A)

2. 不要用from,全部直接用import。

    (適合多層迴圈呼叫:A->B, B->C, C->D, D->A)

---------------------------------------------------------------------------------------------


dict 與 string 互轉:

dict -> string : s = str(d)

string -> dict : d = eval(s)


---------------------------------------------------------------------------------------------


import上層檔案:

package1
|______init__.py
|______init__.pyc
|____common
| |______init__.py
| |______init__.pyc
| |____tools.py
| |____tools.pyc
|____package2
| |______init__.py
| |______init__.pyc
| |____package3
| | |______init__.py
| | |______init__.pyc
| | |____main.py
| | |____test.py
| | |____test.pyc

run.py


run.py:

from package1.package2.package3.test import test

test()


test.py:

from ...common import tools

def test():
    print tools.add(1, 2)


python run.py


關於__init__.py: http://blog.csdn.net/yxmmxy7913/article/details/4233420

python匯入同級別模組很方便:

  import xxx

要匯入下級目錄頁挺方便,需要在下級目錄中寫一個__init__.py檔案

  from dirname import xxx

要匯入上級目錄,可以使用sys.path

  首先sys.path的作用是:當使用import語句匯入模組時,直譯器會搜尋當前模組所在目錄以及sys.path指定的路徑去找需要import的模組

  所以改變思路,直接把上級目錄加到sys.path裡:sys.path.append('../')

  from fatherdirname import xxx


---------------------------------------------------------------------------------------------


disable no-self-use warning:

# pylint: disable=no-self-use


關於pylint報第三方包的錯(no method, no attri), 拿lxml為例:

The reason for this is that pylint by default only trusts C extensions from the standard library and will ignore those that aren't.

As lxml isn't part of stdlib, you have to whitelist it manually. To do this, navigate to the directory of your project in a terminal, and generate an rcfile for pylint:

$ pylint --generate-rcfile > .pylintrc

Then, open that file and edit add lxml to the whitelist like so:

extension-pkg-whitelist=lxml

After that, all E1101 errors regarding lxml should vanish.


---------------------------------------------------------------------------------------------


lxml使用:

from lxml import etree

def test():
    root = etree.Element('xml')
    elem = etree.SubElement(root, 'sender')
    elem.text = etree.CDATA('zyd')
    print etree.dump(root)
    print root.find('sender').text

test()


---------------------------------------------------------------------------------------------


elasticsearch delete scroll

request_addr = es_addr + "/_search/scroll?scroll_id=" + request_json['scroll_id']

requests.delete(request_addr)


---------------------------------------------------------------------------------------------