sockets - How can I overload a built-in module in python? -
I am trying to bind the host to my dragon program. Just affect it in Python program, so I'm not going to modify the I tried to add a bit code to the I found that it works fine. And now I want to know that host-ip translation works only in this dragon program. So my question is: How can I do this socket.py importing my Python program when using To make it clear, this is an example. Suppose 'test' is my work directory: In this case: < How do i / socket import socket What can be the main.py Usage Test / socket.py? How do I test another module / socket? Can I use py? help. But I found out that if the current path ( you import monkey-patch This may be a super-simplification that something like ' Another way to monkey-patch the I like pre-approach, because it is cleaner in the sense because you do not need to go to the inside module, only to hide it out And override some things out / etc / hosts file.
create_connection function in
socket.py for host-IP translation:
host , Replace the original code in port = address # socket.py #: ifadd == "www.google.com": getaddrinfo (host, port, 0, SOCK_STREAM) res = host = target_ip: # root in socket.py Code
import socket ?
exam | --- main.py | --- socket.py
Import socket
'' ) is earlier in the first place of
sys.path and
import socket still imports Built-in Skocket Module
sys.modules , any other module Before placing your own modules instead of the standard
socket , which are using it.
# myscript.py myproject import mysocket import sys sys .Modules ['socket'] = mysocket # ... The rest of your code import request ... < P> For this, whatever the standard
socket is
mysocket
socket >> socket as the # mysocket.py import socket _std_socket * # from everything def create_connection (addresses, * args, ** kwargs): if address == ...: address = ... back _study_socket.create_connection (address, * args, ** kwargs)
socket module automatically, overwrite the names inside the original module.
# myscript.py Import socket DR create_connection2 (...): ... socket.create_connection = create_connection2 # ... rest code import request ...
Comments
Post a Comment