Python module-part2

Source: Internet
Author: User
Tags stdin python script

The modules are divided into three types:

Built-in Modules

Open source Module

Custom Modules


One: Custom modules

1. Defining the module: writing a python file with a function Ftp.py,ftp module name

ftp.py

def get (File_path): print (' Download file%s '%file_path) def put (File_path): print (' Download file%s '%file_path)


2. How to import modules

Import FTP

From FTP import get

From FTP import put as upload

From FTP Import *


3. Namespaces


The nature of 4.import

Importing a module is essentially explaining the execution of a python file

Importing a package is essentially explaining the __init__.py file under the package.


5. Search paths and Sys.path operations



Two: Open source module


1. Define module: Download and install

Way One:

Yum Pipapt-get ...

Way two:

Download source code to extract the source code into the directory compiled source python setup.py build installation source python setup.py install

Note: When using source installation, you need to use the GCC compilation and Python development environment, so you need to do it first:

Yum Install Gccyum install python-devel or apt-get Python-dev

After the installation is successful, the module is automatically installed in a directory in Sys.path, such as:

/usr/lib/python2.7/site-packages/

2. Import module (same as custom module mode)


3:paramiko

I: Download and install

# Pycrypto, because the Paramiko module is internally dependent on Pycrypto, so download and install Pycrypto # download Install Pycryptowget http://files.cnblogs.com/files/wupeiqi/ PYCRYPTO-2.6.1.TAR.GZTAR-XVF pycrypto-2.6.1.tar.gzcd pycrypto-2.6.1python setup.py buildpython setup.py Install # Enter the python environment, import crypto check whether the installation is successful # download install Paramikowget Http://files.cnblogs.com/files/wupeiqi/paramiko-1.10.1.tar.gztar- XVF paramiko-1.10.1.tar.gzcd paramiko-1.10.1python setup.py buildpython setup.py Install # into the Python environment, Import Paramiko Check whether the installation was successful

II. Using modules

1. Login based on user name and password in sshclient mode

Import paramiko# establishes an Sshclient object ssh = Paramiko. Sshclient () # allows trusted hosts to be automatically added to the Host_allow list, which must be placed in front of the Connect method Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) # Call the Connect method to connect to server Ssh.connect (hostname= ' 172.16.209.19 ', port=22,username= ' root ', password= ' 123 ') # Execute command stdin, stdout, stderr = Ssh.exec_command (' df-hl ') # result put in stdout, if there is an error will be placed in stderr print (Stdout.read (). Decode ()) # Close Connection Ssh.close ()

Note: Two more lines are required to run interactive commands in sshclient mode

Import paramiko# establishes an Sshclient object ssh = Paramiko. Sshclient () # allows trusted hosts to be automatically added to the Host_allow list, which must be placed in front of the Connect method Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) # Call the Connect Method connection server Ssh.connect (hostname= ' 172.16.209.119 ', port=22,username= ' root ', password= ' 123 ') # Execute command stdin, stdout, stderr = Ssh.exec_command ("passwd lhf") # result put into stdout, if error will be placed in stderr stdin.write (' 123\n ') Stdin.flush () stdin.write (' 123\n ') Stdin.flush () print (Stderr.read ()) # Close Connection Ssh.close ()


2 Login  

> actually Paramiko. Sshclient (). Connect () The internal implementation of this method calls the transport (). Connect () method. So you can think of transport () as a common way to create a connection inside a Paramiko.

#!/usr/bin/pythonimport paramiko# instantiates a transport object trans = Paramiko. Transport (' 172.16.209.119 ', 22) # Establish connection Trans.connect (username= ' root ', password= ' 123 ') # Specifies the transport of the Sshclient object as the TRANSSSH = Paramiko above. Sshclient () Ssh._transport = trans# Executes the command, like the traditional method stdin, stdout, stderr = Ssh.exec_command (' Df-hl ') print (Stdout.read (). Decode ()) # Close Connection Trans.close ()


3. Sshclient mode login based on public key

#!/usr/bin/pythonimport paramiko# Specifies the local RSA private key file, if a password is set when setting the key pair, password is the set password, such as without specifying the password parameter Pkey = Paramiko. Rsakey.from_private_key_file (' D:\id_rsa ', password= ' 123456 ') # establishes a connection to SSH = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect (hostname= ' 172.16.209.119 ', port=22, username= ' root ', Pkey=pke Y) # Execute command stdin, stdout, stderr = Ssh.exec_command (' Df-hl ') # results put in stdout, if there is an error will be placed in stderr print (Stdout.read (). Decode ()) # Close Connection Ssh.close ()


4. Key-based Transport mode login

#!/usr/bin/pythonimport paramiko# Specifies the local RSA private key file, if a password is set when setting the key pair, password is the set password, such as without specifying the password parameter Pkey = Paramiko. Rsakey.from_private_key_file (' D:\id_rsa ', password= ' 123456 ') # establishes a connection to trans = Paramiko. Transport (' 172.16.209.119 ', ') ' Trans.connect (username= ' root ', pkey=pkey) # Specify Sshclient of the object to be above Transport = Paramiko. Sshclient () Ssh._transport = trans# Executes the command, like the traditional method stdin, stdout, stderr = Ssh.exec_command (' Df-hl ') print (Stdout.read (). Decode ()) # Close Connection Trans.close ()

Upload file SFTP

#!/usr/bin/pythonimport paramiko# instantiates a trans object # instantiates a transport object trans = Paramiko. Transport (' 172.16.209.119 ', 22) # Establishes a connection Trans.connect (username= ' root ', password= ' 123 ') # instantiates an Sftp object, specifying the connected channel SFTP = Paramiko. Sftpclient.from_transport (trans) # Send file Sftp.put (localpath= ' D:\id_rsa ', remotepath= '/tmp/id_rsa ') # download File # sftp.get ( RemotePath, LocalPath) trans.close ()


Three: Built-in modules

    1. OS Module

Used to provide system-level operations

OS.GETCWD ()   Gets the current working directory, which is the directory path of the current Python script work os.chdir ("DirName")    changes the current script working directory, which is equivalent to the shell Cdos.curdir    return current directory:  ('. ') os.pardir   Gets the parent directory string name of the current directory: (' ... ') Os.makedirs (' dirname1/dirname2 ')      can generate multi-level recursive directory Os.removedirs (' dirname1 ')       If the directory is empty, then delete, and recursively to the previous level of the directory, if also empty, then delete, and so on Os.mkdir (' dirname ')      generate a single-level directory, equivalent to the shell mkdir  Dirnameos.rmdir (' dirname ')      Delete single-level empty directory, if the directory is not empty can not be deleted, error; equivalent to Rmdir dirnameos.listdir in the shell (' dirname ')      list all files and subdirectories under the specified directory, including hidden files, and print os.remove ()    Delete a file Os.rename (" Oldname "," NewName ")    Rename File/directory Os.stat (' path/filename ')    get File/directory information os.sep      Output operating system-specific path delimiter, win under "\ \", Linux for "/" os.linesep     output the current platform using the line terminator, win under "\t\n", Linux "\ N "os.pathsep     output string to split file path os.name     output string indicates the current usage platform. Win-> ' nt '; linux-> ' POSIX ' Os.system ("Bash command")  &nBSP; Run shell command, directly display os.environ   get system environment variable Os.path.abspath (path)    return path normalized absolute path Os.path.split ( Path)    split path into a directory and a file name of two tuples returned, it is only the   "path"   in the last   '/'   as a delimiter, separated by the index of 0 as a directory (path), The directory with index 1 as the file name Os.path.dirname (path)    returns path. It is actually the first element of Os.path.split (path)    returns the last file name of path. If path ends with a/or \, then a null value is returned. The second element of Os.path.split (path)    returns true if path exists, or Falseos.path.isabs (path) If path does not exist.    If path is an absolute path, return Trueos.path.isfile (path)    True if path is an existing file. Otherwise, return Falseos.path.isdir (path)    True if path is an existing directory. Otherwise return Falseos.path.join (path1[, path2[,  ...])    returns a combination of multiple paths, the parameters before the first absolute path are ignored Os.path.getatime (path)    Returns the last access time of the file or directory pointed to by Path Os.path.getmtime (path)    returns the last modified time of the file or directory to which path is pointing

Os.path.join Demonstration

>>> os.path.join (' c:\\ ', ' csv ', ' test.csv ') ' C:\\csv\\test.csv ' >>> os.path.join (' Windows\Temp ', ' C : \ \ ', ' csv ', ' test.csv ') ' C:\\csv\\test.csv ' >>> os.path.join ('/home/aa ', '/home/aa/bb ', '/home/aa/bb/c ') '/ Home/aa/bb/c '


This article is from "A Good person" blog, please be sure to keep this source http://egon09.blog.51cto.com/9161406/1840081

Python module-part2

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.