PYTHON learning notes (3)

Source: Internet
Author: User

1. tips of the telnetlib module: (1) the read method in the magical read_very_eager () telnetlib module is of good compatibility. It is perfect in obtaining data integrity and terminator location, however, remember to set the latency and perform the second query after data capturing. (2) telnet directly simulates the data obtained by login and captures some sensitive information records. Reference code:

# Encoding = utf-8def do_telnet (Host, username, password, finish, commands): import telnetlib ''' Telnet remote login: windows client to connect to Linux Server ''' # connect to Telnet server tn = telnetlib. telnet (Host, port = 23, timeout = 10) tn. set_debuglevel (2) # enter the logon username tn. read_until ('login: ') tn. write (username + '\ n') # enter the logon password tn. read_until ('password: ') tn. write (password + '\ n') # Run the tn command after logon. read_until (finish) for command in commands: tn. wri Te ('% s \ n' % command) # After the execution is complete, terminate the Telnet connection (or enter exit to exit) tn. read_until (finish) tn. close () # tn. write ('exit \ n') if _ name __= = '_ main _': # configuration option Host = '10. 255.254.205 '# Telnet server IPusername = 'admin' # login Username password = 'dell1950' # login password finish = ':~ $ '# Command prompt commands = ['echo "test"'] do_telnet (Host, username, password, finish, commands)

 

For details, refer to http://blog.csdn.net/five3/article/details/80999972.multiline problem: (1) when multiple threads share one thing, you can use Queue. Queue to implement control through whether the Queue is empty, and implement lock Signals. (2) abandon the thread to embrace threading. In the past, the younger brother tried to write multiple threads using start_new_thread (), which is more complex in writing and difficult to control threads, and is not as powerful as threading. The new version of py almost abandoned this method. Attached reference code:
import threadingimport timeclass timer(threading.Thread): #The timer class is derived from the class threading.Thread    def __init__(self, num, interval):        threading.Thread.__init__(self)        self.thread_num = num        self.interval = interval        self.thread_stop = False     def run(self): #Overwrite run() method, put what you want the thread do here        while not self.thread_stop:            print 'Thread Object(%d), Time:%s/n' %(self.thread_num, time.ctime())            time.sleep(self.interval)    def stop(self):        self.thread_stop = True def test():    thread1 = timer(1, 1)    thread2 = timer(2, 2)    thread1.start()    thread2.start()    time.sleep(10)    thread1.stop()    thread2.stop()    return if __name__ == '__main__':    test()

 

(3) After the main process ends, it usually takes some time for the sub-process to end. If we want to end the sub-process at the end of the main process, we should use the setDaemon () function. (4) Nothing to say, the lock required for synchronization ==> threading. RLock (), all "Critical Zones" are closed between the acquire () and release () method calls of the same lock object. Reference: http://blog.csdn.net/lazy_tiger/article/details/3861844 ==============================> Python multithreading Learning (serialization) http://www.cnblogs.com/rollenholt/archive/2011/08/09/2131719.html===========> python multithreading Learning (details) (5) setting timeout is not as good as sleep. The former only takes effect when initializing the socket connection. Once the connection is successful, it does not take effect if it waits. Proper sleep can wait until the thread ends to facilitate synchronization. At last, you can use join to set timeout control. 3. Summary of the OS module (1) Simply put, it is to obtain the attributes of file a and then overwrite file B.
Import osimport stat, timeinfile = "samples/sample.jpg" outfile = "out.jpg" # copy contentsfi = open (infile, "rb") fo = open (outfile, "wb ") while 1: s = fi. read (10000) if not s: break fo. write (s) fi. close () fo. close () # copy mode and timestampst = OS. stat (infile) OS. chmod (outfile, stat. s_IMODE (st [stat. ST_MODE]) OS. utime (outfile, (st [stat. ST_ATIME], st [stat. ST_MTIME]) print "original", "= & gt;" print "mode", oct (stat. s_IMODE (st [stat. ST_MODE]) print "atime", time. ctime (st [stat. ST_ATIME]) print "mtime", time. ctime (st [stat. ST_MTIME]) print "copy", "= & gt;" st = OS. stat (outfile) print "mode", oct (stat. s_IMODE (st [stat. ST_MODE]) print "atime", time. ctime (st [stat. ST_ATIME]) print "mtime", time. ctime (st [stat. ST_MTIME]) (2) Command Execution and program Calling execfile () Compile and execute OS .exe cl (path, arg * unzip OS .exe cvp (program, arg *) # specify the program type eval () OS. system (cmd)

 

(3) Use the _ import _ function to obtain the specific function def getfunctionbyname (module_name, function_name): module = _ import _ (module_name) return getattr (module, function_name) print repr (getfunctionbyname ("dumbdbm", "open") (4) use the OS module to call other programs ============================ WIN ========== ==================
import osimport sysdef run(program, *args):    pid = os.fork()    if not pid:        os.execvp(program, (program,) +  args)    return os.wait()[0] run("python", "hello.py")print "goodbye"

 

================================== UNIX ======================== ======
import osimport string def run(program, *args):    # find executable    for path in string.split(os.environ["PATH"], os.pathsep):        file = os.path.join(path, program) + ".exe"        try:            return os.spawnv(os.P_WAIT, file, (file,) + args)        except os.error:            pass    raise os.error, "cannot find executable" run("python", "hello.py")print "goodbye"

 

(5) OS. environ ["PATH"], OS. pathsep ==> System PATH separator, compile Function check syntax

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.