#20 FHS (Filesystem Hierarchy Standard)

2013-09-13

文件系统层次化标准

Version Release date
1.0 1994-02-14
1.1 1994-10-09
1.2 1995-03-28
2.0 1997-10-26
2.1 2000-04-12
2.2 2001-05-23
2.3 2004-01-29
3.0 2015-05-18

基础结构

目录 CentOS 7 Ubuntu 含义
/     根目录
/sys/     sysfs 虚拟FS,内核信息
/proc/     proc 虚拟FS,进程信息
/tmp/     临时文件
/home/     用户主目录
/root/      
/boot/     启动相关:内核 + grub
/bin/ /usr/bin/ /usr/bin/ 系统程序
/sbin/ /usr/sbin/ /usr/sbin/ 系统程序(系统管理)
/lib/ /usr/lib/ /usr/lib/ 动态库
/lib64/ /usr/lib64/ /usr/lib64/ 动态库
/usr/      
/etc/     配置文件
/var/      
/opt/      
/data/      
/srv/      
/dev/     设备
/mnt/     挂载点
/media/     挂载点
/lost+found/ -   使用中的已删除文件
  /run/ /run/  
    /snap/  
    /cdrom/  

/etc/

/var/

目录 含义
/var/log/  
/var/cache/  
/var/mail/  
/var/run/  

PS:较新版本中,/var/run/ 变成了 /run/ 的软链接。

/usr/

UNIX Software Resource

目录 含义
/usr/bin/ 应用程序
/usr/sbin/ 应用程序(系统管理)
/usr/lib/  
/usr/lib64/  
/usr/local/  
/usr/include/  
/usr/share/  
/usr/src/  

PS://usr//usr/local/ 三层具有类似的目录结构
PS:较新版本中 /bin//sbin//lib//lib64//usr/ 目录下的同名目录合并了。

用户主目录

参考资料与拓展阅读

#19 SQLite

2013-07-12

简介

  1. 嵌入式数据库
  2. 第一版 2000 年发布
  3. 公有领域
  4. 实现了大多数 SQL-92 标准,包括事务(ACID)
  5. 使用最广泛的 DB 引擎

命令

.help
.databases
.tables
.shema <tableName> # show sql
.fullschema
.quit

.mode list      # 默认,没有头部,竖线隔开
.mode tabs      # tab 隔开
.mode column    # 可读性强些
.mode line      # 像 MySQL \G
sqlite> .show
        echo: off
         eqp: off
     explain: auto
     headers: off
        mode: list
   nullvalue: ""
      output: stdout
colseparator: "|"
rowseparator: "\n"
       stats: off
       width:
    filename: /tmp/history.db

sqlite> .dbinfo main
database page size:  4096
write format:        2
read format:         2
reserved bytes:      0
file change counter: 3110
database page count: 6669
freelist page count: 0
schema cookie:       7
schema format:       4
default cache size:  0
autovacuum top root: 0
incremental vacuum:  0
text encoding:       1 (utf8)
user version:        2
application id:      0
software version:    3033000
number of tables:    4
number of indexes:   6
number of triggers:  0
number of views:     0
schema size:         785
data version         2

常用操作

查看表结构

.schema tablename
pragma dbname.table_info(tablename)
pragma dbname.table_xinfo(tablename) # 包含虚拟表中的隐藏列
SELECT * FROM sqlite_master WHERE tbl_name = 'tablename';

工具

  1. SQLite Database Browser
  2. heidisql
  3. 浏览器拓展
  4. Navicat for SQLite

附:sqlite help

sqlite> .help
.archive ...             Manage SQL archives
.auth ON|OFF             Show authorizer callbacks
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail on|off             Stop after hitting an error.  Default OFF
.binary on|off           Turn binary output on or off.  Default OFF
.cd DIRECTORY            Change the working directory to DIRECTORY
.changes on|off          Show number of rows changed by SQL
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.connection [close] [#]  Open or close an auxiliary database connection
.databases               List names and files of attached databases
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.dump ?OBJECTS?          Render database content as SQL
.echo on|off             Turn command echo on or off
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.exit ?CODE?             Exit this program with return-code CODE
.expert                  EXPERIMENTAL. Suggest indexes for queries
.explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
.filectrl CMD ...        Run various sqlite3_file_control() operations
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.headers on|off          Turn display of headers on or off
.help ?-all? ?PATTERN?   Show help text for PATTERN
.import FILE TABLE       Import data from FILE into TABLE
.imposter INDEX TABLE    Create imposter table TABLE on index INDEX
.indexes ?TABLE?         Show names of indexes
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.load FILE ?ENTRY?       Load an extension library
.log FILE|off            Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?TABLE?       Set output mode
.nonce STRING            Disable safe mode for one command if the nonce matches
.nullvalue STRING        Use STRING in place of NULL values
.once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.progress N              Invoke progress handler after every N opcodes
.prompt MAIN CONTINUE    Replace the standard prompts
.quit                    Exit this program
.read FILE               Read input from FILE
.recover                 Recover as much data as possible from corrupt db.
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save FILE               Write in-memory database into FILE
.scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.selftest ?OPTIONS?      Run tests defined in the SELFTEST table
.separator COL ?ROW?     Change the column and row separators
.session ?NAME? CMD ...  Create or control sessions
.sha3sum ...             Compute a SHA3 hash of database content
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?ARG?             Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.testcase NAME           Begin redirecting output to 'testcase-out.txt'
.testctrl CMD ...        Run various sqlite3_test_control() operations
.timeout MS              Try opening locked tables for MS milliseconds
.timer on|off            Turn SQL timer on or off
.trace ?OPTIONS?         Output each SQL statement as it is run
.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack
.width NUM1 NUM2 ...     Set minimum column widths for columnar output

#17 Python 可迭代对象

2013-04-30

可迭代对象(Iterable)就是可以用 for 循环遍历的数据结构,包括字符串、元组、列表、字典、集合等内置类型,也可以通过一些方法来是实现自定义可迭代对象。

https://docs.python.org/3/glossary.html#term-iterable
https://docs.python.org/3/glossary.html#term-iterator

迭代协议与序列协议

  • 迭代器协议(Iterator Protocol):如果一个对象包含 __next__ 方法,那就是一个迭代器。

迭代器可以使用 next 函数连续获取数据,内部实现就是调用 __next__ 方法获取一个数据项,如果循环结束,就会抛出 StopIteration

上面讲的是 CPython 实现,实际上 Python 语法规范要求迭代器一定要有 __iter__ 方法。
一般实现中,都有加上 __iter__ 方法,直接 return self

  • 可迭代对象协议(Iterable Protocol):如果一个对象包含 __iter__ 方法(返回一个迭代器对象),那么就是一个可迭代对象,

可以用在 for 循环,zipmapfilter 等需要可迭代对象的场景中。

  • 序列对象协议(Sequence Protocol):如果一个对象包含 __getitem__ 方法(使用 0 开始的整数作为索引),和 __len__ 方法,
    就可以执行一些序列对象的操作,比如...(?)。
    字符串,元组,列表都是序列对象。set 无序,dict 是按 key 索引,所以都不是序列对象。

  • 迭代器协议(Iterator Protocol):如果一个对象包含 __iter__ 方法,和 __next__ 方法,那就是一个迭代器。
    迭代器可以使用 next 函数连续获取数据,内部实现就是调用 __next__ 方法获取一个数据项,如果循环结束,就会抛出 StopIteration
    CPython 没有按照语言规范要求迭代器一定要有 __iter__ 方法。但一般实现中,都是加上 __iter__ 方法,return self

  • https://docs.python.org/3/c-api/abstract.html
  • Iterator Protocol https://docs.python.org/3/c-api/iter.html
  • Sequence Protocol https://docs.python.org/3/c-api/sequence.html

iter

iter(iterable)
iter(callable, sentinel) # sentinel:任意值都行

iter(1)
TypeError: 'int' object is not iterable
iter(1, 1)
TypeError: iter(v, w): v must be callable

iter 用于生成一个迭代器。

  • for 循环遍历的时候,会通过 iter 方法创建一个迭代器。
  • 可以创建迭代器的对象,必须支持 iterable protocol (包含 __iter__() 方法),
    或者支持 sequence protocol (包含 __getitem__() 方法,使用 0 开始的整数作为索引)

原理

迭代器(Iterator)

迭代器是可迭代对象的一种。它是一个具有 __iter__()__next__() 方法的对象,可以逐个返回可迭代对象的元素。
字符串、元组、列表、字典、集合这些内置类型就都不是迭代器。

PEP 234 – Iterators
https://peps.python.org/pep-0234/

自定义可迭代对象

class MyIterable:
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        self.index = 0
        return self

    def __next__(self):
        if self.index < len(self.data):
            result = self.data[self.index]
            self.index += 1
            return result
        else:
            raise StopIteration

a = MyIterable(['apple', 'banana', 'cherry'])
for item in a:
    print(item)

#16 各种链接文件

2013-04-29

Windows 系统

  • 硬链接 Hard Link
  • 同一分区内的文件
  • 软链接 Soft Link / 符号链接 Symbolic Link
  • 文件或目录都行
  • 可以在任何位置,跨磁盘,跨主机
  • 目标位置不存在也没有关系
  • 连接点 Junction,类似软链接,但是需要是本地路径
  • dir 查看目录时显示不同(<SYMLINK><JUNCTION>

PS:Windows 下创建的快捷方式(.lnk 文件)不属于文件链接,在文件系统中也不是透明的存在,只在 图形界面中有用。

$ mklink /?
创建符号链接。

MKLINK [[/D] | [/H] | [/J]] Link Target

        /D      创建目录符号链接。默认为文件
                符号链接。
        /H      创建硬链接而非符号链接。
        /J      创建目录联接。
        Link    指定新的符号链接名称。
        Target  指定新链接引用的路径
                (相对或绝对)。

Linux 系统

只有软链接和硬链接两种,没有 Junction 这种东西混淆视听。

ln -sf src dst  # 创建软链接
ln -Pf src dst  # 创建硬链接
$ ln --help
用法:ln [选项]... [-T] 目标 链接名
 或:ln [选项]... 目标
 或:ln [选项]... 目标... 目录
 或:ln [选项]... -t 目录 目标...
在第一种格式中,创建具有指定<链接名>且指向指定<目标>的链接。
在第二种格式中,在当前目录创建指向<目标>位置的链接。
在第三、四种格式中,在指定<目录>中创建指向指定<目标>的链接。
默认创建硬链接,当使用--symbolic 时创建符号链接。
默认情况下,创建每个目标时不应存在与新链接的名称相同的文件。
创建硬链接时,每个指定的<目标>都必须存在。符号链接可以指向任意的位置;
当链接解析正常时,将其解析为一个相对于其父目录的相对链接。

必选参数对长短选项同时适用。
      --backup[=CONTROL]      为每个已存在的目标文件创建备份文件
  -b                          类似--backup,但不接受任何参数
  -d, -F, --directory         允许超级用户尝试创建指向目录的硬链接
                              (注意:此操作可能因系统限制而失败)
  -f, --force                 强行删除任何已存在的目标文件
  -i, --interactive           删除目标文件前进行确认
  -L, --logical               如目标为符号链接,本次创建链接时将其解引用
  -n, --no-dereference        如果给定<链接名>是一个链接至某目录的符号链接,
                                将其作为普通文件处理
  -P, --physical              创建直接指向符号链接文件的硬链接
  -r, --relative              创建相对于链接位置的符号链接
  -s, --symbolic              创建符号链接而非硬链接
  -S, --suffix=后缀           自行指定备份文件的后缀
  -t, --target-directory=目录  在指定<目录>中创建链接
  -T, --no-target-directory   总是将给定的<链接名>当作普通文件
  -v, --verbose               列出每个链接的文件名称
      --help            显示此帮助信息并退出
      --version         显示版本信息并退出

备份文件的后缀为"~",除非以--suffix 选项或是 SIMPLE_BACKUP_SUFFIX
环境变量指定。版本控制的方式可通过--backup 选项或 VERSION_CONTROL 环境
变量来选择。以下是可用的变量值:

  none, off       不进行备份(即使使用了--backup 选项)
  numbered, t     备份文件加上数字进行排序
  existing, nil   若有数字的备份文件已经存在则使用数字,否则使用普通方式备份
  simple, never   永远使用普通方式备份

使用 -s 选项会忽略 -L 和 -P。
否则当<目标>为一个符号链接(默认为 -P)时,会由最后一个指定的选项来控制行为。

GNU coreutils 在线帮助:<https://www.gnu.org/software/coreutils/>
请向 <http://translationproject.org/team/zh_CN.html> 报告任何翻译错误
完整文档 <https://www.gnu.org/software/coreutils/ln>
或者在本地使用:info '(coreutils) ln invocation'

参考资料与拓展阅读

#15 Python 随机模块

2013-04-17

示例

import string
import random

CHARS1 = string.ascii_letters
CHARS2 = string.ascii_letters + string.digits

def get_random_string(len=5, chars=None):
    if not chars:
        chars = CHARS1
    return ''.join(random.choice(chars) for _ in range(len))

# python3
def get_random_bytes(len=5):
    return bytes(bytearray((random.randrange(256) for _ in range(len))))

# python2
def get_random_bytes(len=5):
    return ''.join(chr(random.randrange(256)) for _ in range(len))

其他 随机字节的方法:

import Cryptodome.Random
Cryptodome.Random.get_random_bytes(size)

In [15]: os.getrandom
Out[15]: <function posix.getrandom(size, flags=0)>

In [17]: os.urandom
Out[17]: <function posix.urandom(size, /)>

#14 计算机专业课程

2013-04-13

计算机的本科教育主要是不变的政治、英语、数学,加上计算机专业课。

  • 政治
  • 英语、专业英语
  • 数学
  • 高等数学(微积分)
  • 离散数学
  • 线性代数
  • 概率论与数理统计
  • 计算机专业课
  • 电气方面
    • 大学物理
    • 模拟电路
    • 数字逻辑(数字电路与逻辑设计)
    • 信号处理原理
    • 系统分析与控制
  • 硬件方面
    • 计算机组成原理
    • 计算机体系结构
    • 微机原理与接口技术
    • 汇编语言
  • 理论课程
    • 操作系统
    • 计算机网络
    • 数据结构与算法
    • 数据库系统原理
    • 编译原理 / 形式语言 / 自动机 / 程序语言理论
    • 软件工程
  • 编程语言
    • C
    • C++
    • Java
    • Python
    • PHP
    • C#
  • 一些杂七杂八的课程(更细致的发展方向)
    • 多媒体技术
    • 相关法律法规
    • Linux 驱动开发
    • 人工智能 / 机器学习 / 自然语言处理
    • 云计算
    • 分布式系统
    • 图形学
    • 机器人工程
    • SQL Server
    • 计算机安全
    • 计算机视觉(CV)
    • 软件测试

PS:我觉得比较重要的五门理论课程加粗了。

参考资料与拓展阅读

#13 ls 按时间排序

2013-04-07
## list, sort by name

# display mtime (默认)
ls -l
# display ctime
ls -lc
ls -l --time=ctime # OR status
# display atime
ls -lu
ls -l --time=atime # OR access, use
# display birth time
ls -l --time=birth # OR creation

## list, sort by time

# sort by mtime
ls -lt
ls -lt --time=mtime
# sort by ctime
ls -ltc
ls -lt --time=ctime
# sort by atime
ls -ltu
ls -lt --time=atime
# sort by birth time
ls -lt --time=birth

助记:

-l # list, sort by name
-t # sort by time
-c # use ctime
-u # use atime
--time=ctime/atime/birth
# 默认时间是 mtime

小实验

# cat /tmp/test.sh
set -xe

rm -f /tmp/a.log

date +%T
touch /tmp/a.log        # brtime, birth time
sleep 1

date +%T
echo "hello world" > /tmp/a.log # mtime, modify time
sleep 1

date +%T
cat /tmp/a.log          # atime, access time
sleep 1

date +%T
chmod 666 /tmp/a.log    # ctime, change time
sleep 1

# date +%T
# echo "nihao" >> /tmp/a.log # mtime, modify time
# sleep 1

stat /tmp/a.log

PS: 修改内容的时候也会更改 ctime