Python -> (9) study notes

Module

Module

All code is written in Python interpreter is lost when exiting interpreter. But when writing large programs that people will tend to code is divided into several different files to use, debugging, and have better readability. In Python module we use to reach these objectives.

A module is a Python definitions and statements of files. File name is the module name with .pythe suffix.

Of the global variable can be __name__obtained module module name (a string).

Now take a look at how the module works. Create a bars.pyfile. Document reads as follows:

"""
Bars Module
============
这是一个打印不同分割线的示例模块
"""
def starbar(num):
    """打印 * 分割线

    :arg num: 线长
    """
    print('*' * num)

def hashbar(num):
    """打印 # 分割线

    :arg num: 线长
    """
    print('#' * num)

def simplebar(num):
    """打印 - 分割线

    :arg num: 线长
    """
    print('-' * num)

Now start the interpreter and import modules:

>>> import bars
>>>

You must use the module name to access functions in the module:

>>> bars.hashbar(10)
##########
>>> bars.simplebar(10)
----------
>>> bars.starbar(10)
**********

Import modules : import module there are different ways. You may be introduced from the specified function module:

>>> from bars import simplebar, starbar
>>> simplebar(20)
--------------------

You can also use from module import *all define the import module, but this is not recommended practice.

package

Contains a __init__.pydirectory of files can be used as a package, all directories in the .pyfile is a sub-module of this package .
Example, first create a mymoduledirectory:

$ cd ~
$ mkdir mymodule

Will be bars.pycopied to the mymoduledirectory;
use touchto create a utils.pyfile;
use touchto create an empty __init__.pyfile.

So if mymodulein the __init__.pyfile contains the following:

from mymodule.bars import simplebar
__all__ = [simplebar, ]

** Only then will simplebar available on import. ** If testing in python3 interpreter needs to be determined is mymoduleperformed at the same level directory directory python3, something like the following, it will lead to ImportError: No module named 'mymodule'an error of.

$ cd /home/shiyanlou
$ python3
>>>

from mymodule import * Only work on an object module level, trying to import functions or classes will cause syntax error.

The default module

Python comes with the installation will install different modules, they can be used as needed, you can also install a new module for the other special purposes.
Here Insert Picture Description
The above example shows how to obtain a list of all modules installed in the system is.

OS module

osModule provides functions related to the operating system. Import it can use the following statement:

>>> import os

getuid()Function returns the current process's effective user id.
getpid()Function returns the id of the current process.
getppid()Returns the id of the parent process.

>>> os.getuid()
500
>>> os.getpid()
16150
>>> os.getppid()
14847

uname()Function returns information identifying the different operating systems, its details in Linux can be returned from the uname -aobtained command. uname()It returns the object is a tuple ( sysname, nodename, release, version, machine).

>>> os.uname()
('Linux', 'd80', '2.6.34.7-56.fc13.i686.PAE', '#1 SMP Wed Sep 15 03:27:15 UTC 2010', 'i686')

getcwd()Function returns the current working directory. chdir(path)It is to change the current directory path. In the first example we see the current working directory is /home/zhangsan, and then we changed to the current working directory /Codeand once again view the current working directory:

>>> os.getcwd()
'/home/zhangsan'
>>> os.chdir('Code')
>>> os.getcwd()
'/home/zhangsan/Code'

Now use the other functions in the os module to create its own function, it will list all files and directories in a given directory:

def view_dir(path='.'):
    """
    这个函数打印给定目录中的所有文件和目录
    :args path: 指定目录,默认为当前目录
    """
    names = os.listdir(path)
    names.sort()
    for name in names:
        print(name, end =' ')
    print()

Examples of the use view_dir () function:

>>> view_dir('/')
.bashrc .dockerenv .profile bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
Requests module

Requests is a third party Python modules, introduces its official website as follows: Requests only a non-transgenic Python HTTP library, humans can safely enjoy.

Third-party modules is not the default module, which means you need to install it using pip3install it.

First of all you want to install pip3:

$ sudo apt-get update
$ sudo apt-get install python3-pip

Then pip3install requests:

$ sudo pip3 install requests

The above command will install Python3 version of Requests module in your system.

You can use the get()method to get any one page

>>> import requests
>>> req = requests.get('https://github.com')
>>> req.status_code
200

reqThe textproperty there server returns an HTML page.

Example, use this knowledge to write a file can be downloaded from the URL specified in the program.

#!/usr/bin/env python3
import requests

def download(url):
    '''
    从指定的 URL 中下载文件并存储到当前目录
    url: 要下载页面内容的网址
    '''
    # 检查 URL 是否存在
    try:
        req = requests.get(url)
    except requests.exceptions.MissingSchema:
        print('Invalid URL "{}"'.format(url))
        return
    # 检查是否成功访问了该网站
    if req.status_code == 403:
        print('You do not have the authority to access this page.')
        return
    filename = url.split('/')[-1]
    with open(filename, 'w') as fobj:
        fobj.write(req.content.decode('utf-8'))
    print("Download over.")

if __name__ == '__main__':
    url = input('Enter a URL: ')
    download(url)

Each module python (python file, which is here download.py) contains a built-in variable __name__, when the module is executed directly, __name__equal to the file name (include the extension .py); If the module importto other modules, the module is __name__equal to the module name (no suffix .py). " __main__" Always refers to the name of the currently executing module (containing the suffix .py). Further when the module is executed directly, __name__ == 'main'the result is true.
if __name__ == '__main__':This statement, its role is only in the current module (module: python file, which is download.py here) called __main__time until the statement is executed within this if block (ie, as when scripts executed). In other words, when this file is imported into another document in the form of modules, in the statement if the block does not perform.

argparse command line parameter processing module

Here is the module is used sys, the command line passed all parameters can be used sys.argvto obtain; if you want to deal with the parameters you can use argparsemodule;

TAB completion

First, create a file: ~/.pythonrc, write the following in the document:

import rlcompleter, readline
readline.parse_and_bind('tab: complete')


history_file = os.path.expanduser('~/.python_history')
readline.read_history_file(history_file)

import atexit
atexit.register(readline.write_history_file, history_file)

The next step in the ~/.bashrcconfiguration file PYTHONSTARTUPenvironment variables to point to this file:

$ export PYTHONSTARTUP=~/.pythonrc

Now, from now on every time you open the bash shell, you will have full TAB complement history and Python interpreter code entered.

To use in the current shell, source the bashrc file.

$ source ~/.bashrc

source

Published 33 original articles · won praise 1 · views 1242

Guess you like

Origin blog.csdn.net/weixin_44783002/article/details/104635282