lib.py輸入Pythonのlibには、パッチ後
#! /usr/bin/python
def gethostbyname(hostname):
print "This is different gethostby name"
return "Hello"
import socket
# Patch the socket library
socket.gethostbyname=gethostbyname
def get():
print socket.gethostbyname("www.google.com")
test1.py
#! /usr/bin/python
import socket
print socket.gethostbyname("www.google.com") # <- this works fine
from lib import get
print get()
print socket.gethostbyname("www.google.com") # <- method is changed
108.177.98.105 # proper output from socket library
This is different gethostby name
Hello
None
This is different gethostby name # <- after import, the gethostbyname method is changed
Hello
test2.py
#! /usr/bin/python
from lib import get
print get()
import socket
print socket.gethostbyname("www.google.com") <- even import again, the socket gethostbyname is changed
This is different gethostby name
Hello
None
This is different gethostby name
Hello
を支配lib.pyファイル内のソケットにgethostbyname、私はインポートそのメソッドはtest * .pyからget()して実行します。ソケットライブラリがインポートされていれば、lib.pyインポートによってオーバーロードされますが、lib.pyを最初にインポートすると、あとでソケットをインポートすると元のソケットシステムライブラリが返されません。
なぜこのように動作していますか?
Python 2.7.10 (default, Feb 7 2017, 00:08:15)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
呼び出しますか? –
@SandeepLadeはい、しました。私の場合、私は何かを働かせるためにMonkey Patchをやっています。 –