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 / etc / hosts file.

I tried to add a bit code to the 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   

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 import socket ?

To make it clear, this is an example. Suppose 'test' is my work directory:

  exam | --- main.py | --- socket.py   

In this case: <

  1. How do i / socket import socket

  2. What can be the main.py Usage Test / socket.py? Import socket

    How do I test another module / socket? Can I use py? help. But I found out that if the current path ( '' ) is earlier in the first place of sys.path and import socket still imports Built-in Skocket Module

    you import monkey-patch 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)   

    This may be a super-simplification that something like ' mysocket.py should look like youd' Languages ​​can be used before adding the languages, but you get this idea.


    Another way to monkey-patch the 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 ...   

    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

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -