《零基础学Python》基于Python的系统管理【十八】

整体文章目录

整体目录

一、 当前章节目录

在这里插入图片描述

二、增强的交互环境IPython

2.1 IPython介绍

  • IPython是一种增强的交互式Python解释器,设计精巧并且具有良好的扩展性。
  • IPython设计的目的是能够创造一个交互式的完整计算环境。
  • IPython具有以下特性:
    1. magic函数:内置了很多函数用来实现各种特性。
    2. Tab补全:可以有效地补齐Python语言的模块、方法和类等。
    3. 源码编辑:可以直接修改源码并运行。
    4. 宏:可以将一段代码定义为一个宏,便于以后运行。
    5. 历史记录:提供了强大的历史记录功能。
    6. 对象自省:有强大的对象自省功能。
    7. 执行系统命令:可以直接在交互式Shell中执行系统命令。

2.2 IPython的安装

Windows下安装步骤

  1. 进入https://pypi.org/project/ipython/下载“ipython-7.25.0-py3-none-any.whl”。
  2. 找到文件所在目录打开命令行输入“pip install ipython-7.25.0-py3-none-any.whl”,等待安装完成即可。

2.3 IPython的启动

# 命令行输入ipython启动IPython解释器

Python 3.8.5 (default, Sep  3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.25.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

2.4 IPython的环境配置

  • Linux系统下是在主目录下的.ipython目录
  • Windows系统下则为C:\Documents and Settings<name>下的_ipython。
  • 具体配置文件为ipy_user_conf.py

三、和IPython的简单交互

3.1 IPython中的输入和输出

In [1]: for i in range(5):
    		print(i)
0
1
2
3
4

In [2]: ls
 驱动器 C 中的卷是 Windows
 卷的序列号是 B2B5-3C8D

 C:\Users\86155\Desktop\Python\第18章 基于Python的系统管理\18.2 和IPython的简单交互 的目录

2021/06/28  21:58    <DIR>          .
2021/06/28  21:58    <DIR>          ..
2021/06/28  21:58    <DIR>          .ipynb_checkpoints
2021/06/28  21:58                72 Untitled.ipynb
               1 个文件             72 字节
               3 个目录 42,741,497,856 可用字节

3.2 输出提示符的区别

In [1]: a = 0

In [2]: b = "IPython"

In [3]: c = [i for i in range(5)]

In [4]: print(a)
0

In [5]: print(b)
IPython

In [6]: print(c)
[0, 1, 2, 3, 4]

In [7]: a
Out[7]: 0

In [8]: b
Out[8]: 'IPython'

In [9]: c
Out[9]: [0, 1, 2, 3, 4]
>>> c = [i for i in range(5)]
>>> print(c)
[0, 1, 2, 3, 4]
>>> c
[0, 1, 2, 3, 4]
>>>

3.3 输出提示符有区别的原因

In [1]: class StrReprDemo(object):
    		def __str__(self):
        		return "StrReprDemo: call the __str__ function"
    		def __repr__(self):
        		return "StrReprDemo: call the __repr__ function"
        
In [2]: srd = StrReprDemo()

In [3]: print(srd)
StrReprDemo: call the __str__ function

In [4]: srd
Out[4]: StrReprDemo: call the __repr__ function

In [5]: class Test():
    		pass
    
In [6]: test = Test()

In [7]: print(test)
<__main__.Test object at 0x00000188575A6CD0>

In [8]: test
Out[8]: <__main__.Test at 0x188575a6cd0>
>>> class StrReprDemo(object):
...     def __str__(self):
...         return "StrReprDemo: call the __str__ function"
...     def __repr__(self):
...         return "StrReprDemo: call the __repr__ function"
>>> srd = StrReprDemo()
>>> print(srd)
StrReprDemo: call the __str__ function
>>> srd
StrReprDemo: call the __repr__ function

四、IPython中的magic函数

4.1 magic函数的使用和构造

In [1]: cd D:\python例题源代码
D:\python例题源代码

In [2]: cd = None

In [3]: cd ...
  File "<ipython-input-2-cddc37357f9b>", line 1
    cd ...
       ^
SyntaxError: invalid syntax

In [4]: %cd ...
D:\python例题源代码

In [5]: del cd

In [6]: cd D:\python例题源代码
D:\python例题源代码

4.2 目录管理

  1. 使用cd切换目录
In [1]: cd C:\Users\86155\Desktop
C:\Users\86155\Desktop

In [2]: cd
C:\Users\86155

In [3]: cd -
C:\Users\86155\Desktop

In [4]: pwd
Out[4]: 'C:\\Users\\86155\\Desktop'

In [5]: cd -q ..

In [6]: pwd
Out[6]: 'C:\\Users\\86155'

In [7]: cd C:\Users\86155\Desktop
C:\Users\86155\Desktop
  1. 使用bookmark管理书签目录
In [1]: cd C:\Users\86155\Desktop
C:\Users\86155\Desktop

In [2]: bookmark py

In [3]: bookmark script C:\Users\86155\Desktop\Python

In [4]: %bookmark -l
Current bookmarks:
py     -> C:\Users\86155\Desktop
script -> C:\Users\86155\Desktop\Python

In [5]: pwd
Out[5]: 'C:\\Users\\86155\\Desktop'

#cd -b <tab>
In [6]: cd -b script
(bookmark:script) -> C:\Users\86155\Desktop\Python
C:\Users\86155\Desktop\Python

In [7]: pwd
Out[7]: 'C:\\Users\\86155\\Desktop\\Python'

In [8]: bookmark tool C:\Users\86155\Desktop\Python\test

In [9]: bookmark -l
Current bookmarks:
py     -> C:\Users\86155\Desktop
script -> C:\Users\86155\Desktop\Python
tool   -> C:\Users\86155\Desktop\Python\test

In [10]: bookmark -d tool

In [11]: bookmark -l
Current bookmarks:
py     -> C:\Users\86155\Desktop
script -> C:\Users\86155\Desktop\Python

In [12]: bookmark -r

In [13]: bookmark -l
Current bookmarks:
  1. 使用dhist查看目录历史
In [14]: %dhist
Directory history (kept in _dh)
0: C:\Users\86155\Desktop\Python\第18章 基于Python的系统管理\18.3 IPython中的magic函数
1: C:\Users\86155\Desktop
2: C:\Users\86155\Desktop\Python

In [15]: cd -01
C:\Users\86155\Desktop

In [16]: cd --Python
C:\Users\86155\Desktop\Python

In [17]: cd --test
No matching entry in directory history

4.3 对象信息的收集

  1. 查看环境变量信息
In [1]: env
Out[1]: {'ALLUSERSPROFILE': 'C:\\ProgramData',
 'APPDATA': 'C:\\Users\\86155\\AppData\\Roaming',
 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files',
 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files',
 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files',
 'COMPUTERNAME': 'LAPTOP-V6B5SQGD',
 'COMSPEC': 'C:\\WINDOWS\\system32\\cmd.exe',
 'DOCKER_TOOLBOX_INSTALL_PATH': 'D:\\Program Files\\Docker Toolbox',
 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData',
 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer',
 'FPS_BROWSER_USER_PROFILE_STRING': 'Default',
 'HOMEDRIVE': 'C:',
 'HOMEPATH': '\\Users\\86155',
 'HTTP_PROXIY': 'http://www.proxy.com:3128',
 'LOCALAPPDATA': 'C:\\Users\\86155\\AppData\\Local',
 'LOGONSERVER': '\\\\LAPTOP-V6B5SQGD',
 'MYSQL_HOME': 'D:\\Program Files\\mysql',
 'NUMBER_OF_PROCESSORS': '8',
 'ONEDRIVE': 'C:\\Users\\86155\\OneDrive',
 'ONEDRIVECONSUMER': 'C:\\Users\\86155\\OneDrive',
 'OS': 'Windows_NT',
 'PATH': 'D:\\anaconda3;D:\\anaconda3\\Library\\mingw-w64\\bin;D:\\anaconda3\\Library\\usr\\bin;D:\\anaconda3\\Library\\bin;D:\\anaconda3\\Scripts;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\NVIDIA Corporation\\NVIDIA NvDLISR;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Docker\\Docker\\resources\\bin;C:\\ProgramData\\DockerDesktop\\version-bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;"D:\\Program Files\\mysql\\bin;";D:\\anaconda3;D:\\anaconda3\\Library\\mingw-w64\\bin;D:\\anaconda3\\Library\\usr\\bin;D:\\anaconda3\\Library\\bin;D:\\anaconda3\\Scripts;C:\\Users\\86155\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\;C:\\Users\\86155\\AppData\\Local\\Programs\\Python\\Python39\\;C:\\Users\\86155\\AppData\\Local\\Microsoft\\WindowsApps;D:\\Program Files\\Docker Toolbox;D:\\Program Files\\JetBrains\\PyCharm Community Edition 2021.1.1\\bin;',
 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC',
 'PROCESSOR_ARCHITECTURE': 'AMD64',
 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 126 Stepping 5, GenuineIntel',
 'PROCESSOR_LEVEL': '6',
 'PROCESSOR_REVISION': '7e05',
 'PROGRAMDATA': 'C:\\ProgramData',
 'PROGRAMFILES': 'C:\\Program Files',
 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)',
 'PROGRAMW6432': 'C:\\Program Files',
 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules',
 'PUBLIC': 'C:\\Users\\Public',
 'PYCHARM COMMUNITY EDITION': 'D:\\Program Files\\JetBrains\\PyCharm Community Edition 2021.1.1\\bin;',
 'SESSIONNAME': 'Console',
 'SYSTEMDRIVE': 'C:',
 'SYSTEMROOT': 'C:\\WINDOWS',
 'TEMP': 'C:\\Users\\86155\\AppData\\Local\\Temp',
 'TMP': 'C:\\Users\\86155\\AppData\\Local\\Temp',
 'USERDOMAIN': 'LAPTOP-V6B5SQGD',
 'USERDOMAIN_ROAMINGPROFILE': 'LAPTOP-V6B5SQGD',
 'USERNAME': '86155',
 'USERPROFILE': 'C:\\Users\\86155',
 'WINDIR': 'C:\\WINDOWS',
 'ZES_ENABLE_SYSMAN': '1',
 'CONDA_PREFIX': 'D:\\anaconda3',
 'JPY_INTERRUPT_EVENT': '2364',
 'IPY_INTERRUPT_EVENT': '2364',
 'JPY_PARENT_PID': '1428',
 'TERM': 'xterm-color',
 'CLICOLOR': '1',
 'PAGER': 'cat',
 'GIT_PAGER': 'cat',
 'MPLBACKEND': 'module://ipykernel.pylab.backend_inline'}
  1. 使用page处理输出信息

在这里插入图片描述

  1. 使用pfile命令
In [3]: import os

In [4]: pfile os
Out[4]: r"""OS routines for NT or Posix depending on what system we're on.

This exports:
  - all functions from posix or nt, e.g. unlink, stat, etc.
  - os.path is either posixpath or ntpath
  - os.name is either 'posix' or 'nt'
  - os.curdir is a string representing the current directory (always '.')
  - os.pardir is a string representing the parent directory (always '..')
# 省略部分代码
  1. 使用pdef、pdoc和pinfo查看对象信息
In [5]: def add(x, y):
    		"""This is a simple addition"""
    		return (x + y)

In [6]: pdef add
add(x, y)

In [7]: pdoc add
Class docstring:
    This is a simple addition
Call docstring:
    Call self as a function.

In [8]: pinfo add
Signature: add(x, y)
Docstring: This is a simple addition
File:      c:\users\86155\desktop\python\第18章 基于python的系统管理\18.3 ipython中的magic函数\<ipython-input-4-b9622a23dda2>
Type:      function
  1. 使用psearch查找对象信息
In [9]: psearch a*
abs
add
all
any
ascii

In [10]: psearch -e builtin a*
add

4.4 magic函数小结

在这里插入图片描述

五、IPython适合于系统管理的特点

5.1 Tab补全

  1. Tab补全使用
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
In [1]: import sys

In [2]: platform = sys.platform

In [3]: print(plat<TAB>)

In [3]: print(platform)
win32
  1. Tab补全的两种方式
    在这里插入图片描述

5.2 历史记录功能

  1. history命令的使用
In [1]: a = 0

In [2]: b = "IPython"

In [3]: c = [i for i in range(5)]

In [4]: cd C:\Users\86155\Desktop
C:\Users\86155\Desktop

In [5]: history
a = 0
b = "IPython"
c = [i for i in range(5)]
cd C:\Users\86155\Desktop
history

In [6]: history -n
   1: a = 0
   2: b = "IPython"
   3: c = [i for i in range(5)]
   4: cd C:\Users\86155\Desktop
   5: history
   6: history -n
  1. 历史记录中的查找
In [7]: history -g history
   5: history
   6: history -n
   7: history -g history
  1. 使用_符号访问输出结果
In [8]: test = "IPython"

In [9]: _
Out[9]: ''

In [10]: test
Out[10]: 'IPython'

In [11]: _
Out[11]: 'IPython'

In [12]: test = _

In [13]: test
Out[13]: 'IPython'
>>> test = "Python"
>>> _
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> test
'Python'
>>> _
'Python'

5.3 执行外部系统命令和运行文件

  1. 使用!执行外部系统命令
In [1]: cd D:\anaconda3

In [2]: !dir
 驱动器 D 中的卷是 Data
 卷的序列号是 C2B5-D694

 D:\anaconda3 的目录

2021/05/31  13:39    <DIR>          .
2021/05/31  13:39    <DIR>          ..
2021/05/31  13:39                 0 .nonadmin
# 省略部分输出
2018/04/20  23:28            19,208 api-ms-win-core-console-l1-1-0.dll
2018/04/20  23:28            18,696 api-ms-win-core-datetime-l1-1-0.dll
2018/04/20  23:28            18,696 api-ms-win-core-debug-l1-1-0.dll
2018/04/20  23:28            18,696 api-ms-win-core-errorhandling-l1-1-0.dll

2020/11/13  20:51        19,309,814 _conda.exe
              65 个文件     42,454,095 字节
              23 个目录 91,033,182,208 可用字节

In [3]: pattern = "*.exe"

In [4]: !dir $pattern
 驱动器 D 中的卷是 Data
 卷的序列号是 C2B5-D694

 D:\anaconda3 的目录

2020/09/04  10:30            95,232 python.exe
2020/09/04  10:30            93,696 pythonw.exe
2021/05/02  16:03           319,076 Uninstall-Anaconda3.exe
2020/09/04  10:29           518,144 venvlauncher.exe
2020/09/04  10:29           517,120 venvwlauncher.exe
2020/11/13  20:51        19,309,814 _conda.exe
               6 个文件     20,853,082 字节
               0 个目录 91,033,182,208 可用字节

  1. 使用!操作符需要注意的问题
In [5]: !dir $(pattern[:-3]+"dll")
 驱动器 D 中的卷是 Data
找不到文件

 卷的序列号是 C2B5-D694

 D:\anaconda3 的目录
 
In [6]: new_pattern = pattern[:-3] + "dll"

In [7]: !dir $new_pattern
 驱动器 D 中的卷是 Data
 卷的序列号是 C2B5-D694

 D:\anaconda3 的目录

2018/04/20  23:28            19,208 api-ms-win-core-console-l1-1-0.dll
2018/04/20  23:28            18,696 api-ms-win-core-datetime-l1-1-0.dll
2018/04/20  23:28            18,696 api-ms-win-core-debug-l1-1-0.dll
2018/04/20  23:28            18,696 api-ms-win-core-errorhandling-l1-1-0.dll
# 省略部分代码
              52 个文件      8,631,320 字节
               0 个目录 91,033,182,208 可用字节

In [8]: !type test.txt
This is a file for testing
  1. 将系统命令输出赋值给Python变量
In [9]: result = !dir $pattern

In [10]: result
Out[10]: [' 驱动器 D 中的卷是 Data',
 ' 卷的序列号是 C2B5-D694',
 '',
 ' D:\\anaconda3 的目录',
 '',
 '2020/09/04  10:30            95,232 python.exe',
 '2020/09/04  10:30            93,696 pythonw.exe',
 '2021/05/02  16:03           319,076 Uninstall-Anaconda3.exe',
 '2020/09/04  10:29           518,144 venvlauncher.exe',
 '2020/09/04  10:29           517,120 venvwlauncher.exe',
 '2020/11/13  20:51        19,309,814 _conda.exe',
 '               6 个文件     20,853,082 字节',
 '               0 个目录 91,033,182,208 可用字节']
  1. 运行外部文件
# test.py
def hello(arg):
    print("Hello,", arg)
    
hello("IPython")
In [11]: !python test.py
Hello, IPython

In [12]: %run test.py
Hello, IPython

5.4 对象查看和自省

In [1]:  import sys

In [2]: print(dir(sys))
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__', '_base_executable', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_framework', '_getframe', '_git', '_home', '_xoptions', 'addaudithook', 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'ps3', 'pycache_prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info', 'warnoptions', 'winver']
  1. ?和??操作符的使用
In [1]: import os

In [2]: os.system?
Signature: os.system(command)
Docstring: Execute the command in a subshell.
Type:      builtin_function_or_method

In [3]: os.mkdir??
Signature: os.mkdir(path, mode=511, *, dir_fd=None)
Docstring:
Create a directory.

If dir_fd is not None, it should be a file descriptor open to a directory,
  and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
  If it is unavailable, using it will raise a NotImplementedError.

The mode argument is ignored on Windows.
Type:      builtin_function_or_method

In [4]: %sx??
Source:
    @line_cell_magic
    def sx(self, line='', cell=None):
        """Shell execute - run shell command and capture output (!! is short-hand).
# 省略部分输出
  1. 使用who、who_ls和whos查看对象信息
In [1]: a = 0

In [2]: b = "IPython"

In [3]: c = [i for i in range(5)]

In [4]: who
a	 b	 c	 os	 sys	 

In [5]: who int
a	 

In [6]: who str
b	 

In [7]: who list
c	

In [8]: who_ls
Out[8]: ['a', 'b', 'c', 'os', 'sys']

In [9]: who_ls int
Out[9]: ['a']

In [10]: print(_)
['a']

In [11]: whos
Variable   Type      Data/Info
------------------------------
a          int       0
b          str       IPython
c          list      n=5
os         module    <module 'os' from 'D:\\anaconda3\\lib\\os.py'>
sys        module    <module 'sys' (built-in)>

5.5 直接编辑代码

  1. edit命令的使用
# 编辑器中加入
def prime_numbers(number):
    primenumAll = [2]
    for i in range(2, number):
        pnum = []
        for j in range(2, i):
            if(i % j==0):
                break
            else:
                pnum.append(i)
            if len(pnum) == i-2:
                primenumAll.append(i)
    print(primenumAll)
In [1]: edit
IPython will make a temporary file named: C:\Users\86155\AppData\Local\Temp\ipython_edit_2e4ffacs\ipython_edit_qm6sb5jf.py
Editing... done. Executing edited code...
Out[1]: 'def prime_numbers(number):\n    primenumAll = [2]\n    for i in range(2, number):\n        pnum = []\n        for j in range(2, i):\n            if(i % j==0):\n                break\n            else:\n                pnum.append(i)\n            if len(pnum) == i-2:\n                primenumAll.append(i)\n    print(primenumAll)'

In [2]: prime_numbers(34)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
  1. 对上一次代码进行修改
edit -p
  1. 修改而不执行代码
In [3]: edit -x
IPython will make a temporary file named: C:\Users\86155\AppData\Local\Temp\ipython_edit_murl227o\ipython_edit_nuuoqql3.py
Editing...
Out[3]: 'def prime_numbers(number):\n    primenumAll = [2]\n    for i in range(2, number):\n        pnum = []\n        for j in range(2, i):\n            if(i % j==0):\n                break\n            else:\n                pnum.append(i)\n            if len(pnum) == i-2:\n                primenumAll.append(i)\n    print(primenumAll)\n'

5.6 设置别名和宏

  1. 设置别名
In [1]: alias ns netstat -an

In [2]: ns

活动连接

  协议  本地地址          外部地址        状态
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:3306           0.0.0.0:0              LISTENING
# 省略部分输出

In [3]: alias myecho echo "Input: <%l>"

In [4]: myecho test
"Input: <test>" 

In [5]: alias myecho2 echo first %s second %s

In [6]: myecho2 arg1 arg2
first arg1 second arg2 

In [7]: myecho2 arg1
UsageError: Alias <myecho2> requires 2 arguments, 1 given.
  1. 设置宏

代码
In [1]: import datetime

In [2]: datetime.date.today() + datetime.timedelta(days=1)
Out[2]: datetime.date(2021, 6, 30)

In [3]: macro tomorrow 2
Macro `tomorrow` created. To execute, type its name (without quotes).
=== Macro contents: ===
datetime.date.today() + datetime.timedelta(days=1)
 
In [4]: tomorrow
Out[4]: datetime.date(2021, 6, 30)

In [5]: macro
Out[5]: ['tomorrow']

六、使用Python进行文件管理

6.1 文件的比较

# 在当前目录下text1.txt、text2.txt没有任何内容,text3.txt文件中有一些随意写入的数据。
In [1]: import filecmp

In [2]: filecmp.cmp("text1.txt","text2.txt")
Out[2]: True

In [3]: filecmp.cmp("text1.txt","text3.txt")
Out[3]: False

# 将text3.txt清空
In [4]: !tree /F
卷 Windows 的文件夹 PATH 列表
卷序列号为 B2B5-3C8D
C:.
│  text1.txt
│  text2.txt
│  text3.txt
│  Untitled.ipynb
│  
├─.ipynb_checkpoints
│      Untitled-checkpoint.ipynb
│      
├─test1
│      text1.txt
│      text2.txt
│      text3.txt
│      
└─test2
        text1.txt
        text3.txt
        
In [5]: filecmp.cmpfiles("test1", "test2", ["text1.txt", "text2.txt", "text3.txt"])
Out[5]: (['text1.txt'], ['text3.txt'], ['text2.txt'])

In [6]: result = filecmp.dircmp("test1", "test2")

In [7]: result.report()
diff test1 test2
Only in test1 : ['text2.txt']
Identical files : ['text1.txt']
Differing files : ['text3.txt']

在这里插入图片描述

6.2 文件的归档

In [1]: import tarfile

In [2]: tar = tarfile.open("textfile.tar", "w")

In [3]: tar.add("text1.txt")

In [4]: tar.add("text2.txt")

In [5]: tar.add("text3.txt")

In [6]: tar.add("test1")

In [7]: tar.add("test2")

In [8]: tar.close()

In [9]: tar = tarfile.open("textfile.tar", "r")

In [10]: tar.list()
?rw-rw-rw- 0/0          0 2021-06-29 22:58:27 text1.txt 
?rw-rw-rw- 0/0          0 2021-06-29 22:58:27 text2.txt 
?rw-rw-rw- 0/0          9 2021-06-29 22:58:56 text3.txt 
?rwxrwxrwx 0/0          0 2021-06-29 23:10:22 test1/ 
?rw-rw-rw- 0/0          0 2021-06-29 22:58:27 test1/text1.txt 
?rw-rw-rw- 0/0          0 2021-06-29 22:58:27 test1/text2.txt 
?rw-rw-rw- 0/0          0 2021-06-29 23:12:52 test1/text3.txt 
?rwxrwxrwx 0/0          0 2021-06-29 23:13:57 test2/ 
?rw-rw-rw- 0/0          0 2021-06-29 22:58:27 test2/text1.txt 
?rw-rw-rw- 0/0          9 2021-06-29 22:58:56 test2/text3.txt 

In [11]: tar.close()

In [12]: tar = tarfile.open("textfile.tar", "r")

In [13]: tar.getnames()
Out[13]: ['text1.txt',
 'text2.txt',
 'text3.txt',
 'test1',
 'test1/text1.txt',
 'test1/text2.txt',
 'test1/text3.txt',
 'test2',
 'test2/text1.txt',
 'test2/text3.txt']

In [14]: tar.name
Out[14]: 'C:\\Users\\86155\\Desktop\\Python\\第18章 基于Python的系统管理\\18.5 使用Python进行文件管理\\textfile.tar'

In [15]: tar.members
Out[15]: [<TarInfo 'text1.txt' at 0x250ef725100>,
 <TarInfo 'text2.txt' at 0x250ef725280>,
 <TarInfo 'text3.txt' at 0x250ef725580>,
 <TarInfo 'test1' at 0x250ef725340>,
 <TarInfo 'test1/text1.txt' at 0x250ef725400>,
 <TarInfo 'test1/text2.txt' at 0x250ef7254c0>,
 <TarInfo 'test1/text3.txt' at 0x250ef7251c0>,
 <TarInfo 'test2' at 0x250ef725640>,
 <TarInfo 'test2/text1.txt' at 0x250ef725700>,
 <TarInfo 'test2/text3.txt' at 0x250ef7257c0>]

In [16]: tar.extractall("tmp")

In [17]: !tree /F
卷 Windows 的文件夹 PATH 列表
卷序列号为 B2B5-3C8D
C:.
│  text1.txt
│  text2.txt
│  text3.txt
│  textfile.tar
│  Untitled.ipynb
│  Untitled1.ipynb
│  
├─.ipynb_checkpoints
│      Untitled-checkpoint.ipynb
│      Untitled1-checkpoint.ipynb
│      
├─test1
│      text1.txt
│      text2.txt
│      text3.txt
│      
├─test2
│      text1.txt
│      text3.txt
│      
└─tmp
    │  text1.txt
    │  text2.txt
    │  text3.txt
    │  
    ├─test1
    │      text1.txt
    │      text2.txt
    │      text3.txt
    │      
    └─test2
            text1.txt
            text3.txt

6.3 文件的压缩

In [1]: f = open("large.txt", "w")

In [2]: for i in range(200000):
    f.write("IPython is an enhanced interactive Python shell")
    
In [3]: f.close()

In [4]: ls
 驱动器 C 中的卷是 Windows
 卷的序列号是 B2B5-3C8D

 C:\Users\86155\Desktop\Python\第18章 基于Python的系统管理\18.5 使用Python进行文件管理 的目录

2021/06/30  10:49    <DIR>          .
2021/06/30  10:49    <DIR>          ..
2021/06/30  10:27    <DIR>          .ipynb_checkpoints
2021/06/30  10:49         9,400,000 large.txt
2021/06/29  23:10    <DIR>          test1
2021/06/29  23:13    <DIR>          test2
2021/06/29  22:58                 0 text1.txt
2021/06/29  22:58                 0 text2.txt
2021/06/29  22:58                 9 text3.txt
2021/06/30  09:17            20,480 textfile.tar
2021/06/30  09:23    <DIR>          tmp
2021/06/29  23:29             3,106 Untitled.ipynb
2021/06/30  10:27             6,382 Untitled1.ipynb
2021/06/30  10:49             1,057 Untitled2.ipynb
               8 个文件      9,431,034 字节
               6 个目录 42,386,960,384 可用字节
               
In [5]: import tarfile

In [6]: tar = tarfile.open("large.tar.gz", "w:gz")

In [7]: tar.add("large.txt")

In [8]: tar.close()

In [9]: ls
 驱动器 C 中的卷是 Windows
 卷的序列号是 B2B5-3C8D

 C:\Users\86155\Desktop\Python\第18章 基于Python的系统管理\18.5 使用Python进行文件管理 的目录

2021/06/30  10:51    <DIR>          .
2021/06/30  10:51    <DIR>          ..
2021/06/30  10:27    <DIR>          .ipynb_checkpoints
2021/06/30  10:51            27,578 large.tar.gz
2021/06/30  10:49         9,400,000 large.txt
2021/06/29  23:10    <DIR>          test1
2021/06/29  23:13    <DIR>          test2
2021/06/29  22:58                 0 text1.txt
2021/06/29  22:58                 0 text2.txt
2021/06/29  22:58                 9 text3.txt
2021/06/30  09:17            20,480 textfile.tar
2021/06/30  09:23    <DIR>          tmp
2021/06/29  23:29             3,106 Untitled.ipynb
2021/06/30  10:27             6,382 Untitled1.ipynb
2021/06/30  10:51             2,899 Untitled2.ipynb
               9 个文件      9,460,454 字节
               6 个目录 42,386,833,408 可用字节

七、使用Python定时执行任务

7.1 使用休眠功能

# 每过60秒在终端上显示当前计算机的网络连接
import time
import os

def main(cmd, inc=60):
    while True:
        os.system(cmd)
        time.sleep(inc)

main("netstat -an", 60)

7.2 使用sched模块来定时执行任务

import time, os
import sched

schedule = sched.scheduler(time.time, time.sleep)

def execute_command(cmd, inc):
    os.system(cmd)
    schedule.enter(inc, 0, execute_command, (cmd, inc))

def main(cmd, inc=60):
    schedule.enter(0, 0, execute_command, (cmd, inc))
    schedule.run()

main("netstat -an", 60)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值