[Linux] Python code modularization

***

Task 5:

Create a py file in the directory and run it. Key points: python os and sys system interface, file interface

Step 1: learn the functions of os module in python to process files and directories

The os module provides very rich methods for processing files and directories. Common methods are as follows. For more methods, please refer to: https://www.runoob.com/python/os-file-methods.html.

Serial numberMethod and description
1os.access(path, mode) verifies the permission mode
2os.chdir(path) changes the current working directory
3os.chflags(path, flags) sets the flag of the path as a numeric flag.
4os.chmod(path, mode)
5os.chown(path, uid, gid)

Step 2: Learn sys module and parameter transfer function under python

A module is a file that contains all the functions and variables you define, with the suffix. py. The module can be introduced by other programs to use the functions in the module. This is also the way to use the python standard library.
Refer to: https://www.runoob.com/python3/python3-module.html
If testing on win:

# -*- coding: utf-8 -*-
"""
Created on Sat Nov 20 08:49:33 2021

@author: 86493
"""
import sys 
print('The command line parameters are as follows:')
for i in sys.argv:
    print(i)
    
print('\n\nPython The path is:', sys.path, '\n')

The result is:

The command line parameters are as follows:
D:\Desktop files\matrix\code\Linux\sys_test.py


Python The path is: ['D:\\anaconda1\\envs\\tensorflow\\python38.zip', 'D:\\anaconda1\\envs\\tensorflow\\DLLs', 'D:\\anaconda1\\envs\\tensorflow\\lib', 'D:\\anaconda1\\envs\\tensorflow', '', 'D:\\anaconda1\\envs\\tensorflow\\lib\\site-packages', 'D:\\anaconda1\\envs\\tensorflow\\lib\\site-packages\\win32', 'D:\\anaconda1\\envs\\tensorflow\\lib\\site-packages\\win32\\lib', 'D:\\anaconda1\\envs\\tensorflow\\lib\\site-packages\\Pythonwin', 'D:\\anaconda1\\envs\\tensorflow\\lib\\site-packages\\IPython\\extensions', 'C:\\Users\\86493\\.ipython'] 

1. import sys introduces the sys.py module in the python standard library; This is the first mock exam.
2. sys.argv is a list of command line arguments.
3. sys.path contains a list of paths where the Python interpreter automatically finds the required modules.

Step 3:

Under the previous home/coggle directory in ubuntu, in the folder of your English nickname (no space in the middle), create a new test5.py file (through the touch command). The program can use os and sys modules to complete the following functions:

  • Function 1: print command line parameters Python
Command line input:
python3 test5.py Parameter 1 Parameter 2
 Program output:
test5.py
 Parameter 1
 Parameter 2


The test5.py file code is:

import sys
lis = sys.argv[1:]
if len(lis) < 2:
    raise Exception("Two parameters must be passed in")
print(f"test5.py\n{lis[0]}\n{lis[1]}")
  • Function 2: use os module to print all files starting with m in / usr/bin / path.
# !/usr/bin/python3
## -*- f= coding:utf-8 -*-

import sys
import os
pth = os.listdir("/usr/bin")
ans = []

for file_dir in pth:
    name = file_dir.split('/')[-1]
    if not os.path.isdir("/usr/bin" + name) and name.startswith('m'):
        ans.append(name)

print(ans)

The results printed after running are:

andy@ubuntu:~/coggle$ vim test5_2.py
andy@ubuntu:~/coggle$ python3 test5_2.py
['mshowfat', 'md5sum', 'mtr', 'mktemp', 'mxtar', 'mako-render', 'mesa-overlay-control.py', 'mimetype', 'mdeltree', 'm2400w', 'mcheck', 'mcookie', 'mcopy', 'mawk', 'mandb', 'mtrace', 'mesg', 'mtoolstest', 'mmd', 'make-first-existing-target', 'mdu', 'mkzftree', 'mcomp', 'mt-gnu', 'mformat', 'mountpoint', 'manpath', 'mk_modmap', 'mcat', 'mkfontscale', 'mutter', 'mapscrn', 'mtr-packet', 'man-recode', 'mv', 'mmcli', 'mkfontdir', 'msexpand', 'mpartition', 'mscompress', 'mren', 'mzip', 'mdig', 'mousetweaks', 'mt', 'minfo', 'mmount', 'mcd', 'mkmanifest', 'mlabel', 'md5sum.textutils', 'mkfifo', 'mimeopen', 'mdir', 'mdel', 'mknod', 'm2300w-wrapper', 'mkisofs', 'min12xxw', 'mattrib', 'more', 'mclasserase', 'mmove', 'migrate-pubring-from-classic-gpg', 'make', 'mrd', 'mount', 'man', 'mtype', 'm2300w', 'monitor-sensor', 'mshortname', 'mkdir', 'mksquashfs', 'mtools', 'mbadblocks']

Task 6:

Create a py directory under the directory and import. Key points: modularization of python code

Step 1: Learn python modularization,

Refer to: https://www.runoob.com/python3/python3-module.html

When we use the import statement, how does the Python interpreter find the corresponding file?
This involves the python search path, which is composed of a series of directory names, and the Python interpreter looks for the introduced modules from these directories in turn.
This looks like an environment variable. In fact, you can also determine the search path by defining environment variables.

The search path is determined when Python is compiled or installed. Installing a new library should also be modified. The search path is stored in the path variable in the sys module. Do a simple experiment. In the interactive interpreter, enter the following code:

andy@ubuntu:~/coggle$ python3
Python 3.8.2 (default, Nov 15 2021, 19:16:38) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/local/lib/python38.zip', '/usr/local/lib/python3.8', '/usr/local/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/site-packages']

The sys.path output is a list, in which the first item is an empty string '', representing the current directory (if printed from a script, you can see which directory it is more clearly), that is, the directory where we execute the python interpreter (for a script, it is the directory where the running script is located).

Therefore, if a file with the same name as the module to be imported exists in the current directory, the module to be imported will be shielded.

be careful:
(1) rom... Import * can import all the contents of the module, but this declaration should not be used too much.

Step 2: create the affairs folder

In the / home/coggle directory, create an affairs folder in the folder of your English nickname (no space in the middle).

Step 3: functional requirements

Write test6.py and affairs.py to complete the following functions:

  • Function 1: affairs.py code completion https://mirror.coggle.club/dataset/affairs.txt For file reading, you can directly pd.read here_ csv(' https://mirror.coggle.club/dataset/affairs.txt '). This part is written as a function.
  • Function 2: test6.py can import affairs.py code
  • Function 3: test6.py can parse the command line and output the specific lines of affairs.txt.

File directory:

/home/coggle/ 
     Your English nickname named folder/        
             test6.py        
             affairs/            
                        affairs.py

Implementation requirements:

stay/home/coggle/Your English nickname named folder/Directory, you can execute:

python3 test6.py 10
 No, bugļ¼ŒAnd complete the output of the tenth line.

test6.py file:

# !/usr/bin/python3
## -*- f=coding:utf-8 -*-

# test6.py
import sys
from affairs.affairs import read_affairs
params = sys.argv[1:]
if not len(params):
    params = [0]
read_display([int(p) for p in params])

affairs.py file:

# affairs.py
import pandas as pd

def read_affairs(rows):
    # rows is not an integer, but a list
    df = pd.read_csv("https://mirror.coggle.club/dataset/affairs.txt")
    print(df.loc[rows])

be careful:
(1) Note: if ubuntu does not install Chinese input method, you can refer to this article: Install Sogou input method for Ubuntu.
(2) If ubuntu has not installed pandas and other tools, please refer to About installing and configuring numpy,scipy,matplotlibm,pandas and sklearn under Ubuntu,ubuntu installing pandas.

Reference

coggle30 day machine learning punch in Linux

Keywords: Python Linux

Added by WebbieDave on Sat, 20 Nov 2021 19:59:27 +0200