首页 > 系统相关 >Python 运行 shell 命令的一些方法

Python 运行 shell 命令的一些方法

时间:2023-07-17 19:23:05浏览次数:38  
标签:shell 模块 Python 命令 sh file print new os

哈喽大家好,我是咸鱼

我们知道,python 在自动化领域中被广泛应用,可以很好地自动化处理一些任务

就比如编写 Python 脚本自动化执行重复性的任务,如文件处理、数据处理、系统管理等需要运行其他程序或者与操作系统交互的任务

那么今天我们来看一下在 python 中如何运行 shell 命令来与操作系统交互

一般来讲,最好是用 python 自带的函数或模块,而不是直接调用其他程序或者操作系统的命令

我们来看一下 python 中有哪些自带模块或者方法可以实现

pathlib 模块

如果你需要创建或者删除文件/目录,检查文件是否存在或者改变权限等,你完全不需要使用操作系统的命令

你可以完全通过 pathlib 模块来实现,它有你需要的一切,甚至 globos.path 都可以不用

我们来简单看一下关于这个模块的例子

from pathlib import Path

# 创建一个Path对象表示当前工作目录
current_directory = Path.cwd()
print("当前工作目录:", current_directory)

# 创建一个新的目录
new_directory = current_directory / "my_folder"
new_directory.mkdir()
print("创建新目录:", new_directory)

# 创建一个新的文件
new_file = new_directory / "my_file.txt"
new_file.touch()
print("创建新文件:", new_file)

# 写入文件
with new_file.open(mode='w') as f:
    f.write("Hello, World!")

# 读取文件内容
with new_file.open() as f:
    content = f.read()
print("文件内容:", content)

# 遍历目录中的文件
for file in new_directory.iterdir():
    print("文件:", file)

# 删除文件和目录
new_file.unlink()
new_directory.rmdir()
print("删除文件和目录:", new_file, new_directory)

tempfile 模块

在 Python 中临时创建和处理文件时,tempfile 模块提供了方便的方法

它可以在临时目录中创建临时文件和临时文件夹,并提供了一些便利的函数和类来管理这些临时文件

import tempfile

# 创建临时文件
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.write(b'This is a temporary file.')
temp_file.close()

# 打印临时文件路径
print("临时文件路径:", temp_file.name)

# 打开临时文件并读取内容
with open(temp_file.name, 'r') as f:
    content = f.read()
print("临时文件内容:", content)

# 创建临时目录
temp_dir = tempfile.TemporaryDirectory()

# 打印临时目录路径
print("临时目录路径:", temp_dir.name)

# 自动清理临时目录
temp_dir.cleanup()

shutil 模块

前面我们知道 pathlib 模块满足了 python 中大多数与文件相关的需求

如果需要例如复制,移动,删除或创建文件,可以使用 shutil 模块

import shutil

# 复制文件
shutil.copy('source_file.txt', 'destination_folder/')

# 移动文件
shutil.move('source_file.txt', 'destination_folder/')

# 删除文件
shutil.remove('file_to_be_deleted.txt')

# 删除目录
shutil.rmtree('directory_to_be_deleted/')

# 创建压缩文件
shutil.make_archive('archive', 'zip', 'source_folder/')

# 解压缩文件
shutil.unpack_archive('archive.zip', 'destination_folder/')

os 模块

os 模块是 Python 中一个更老的、更底层的模块,提供了与操作系统交互和执行文件系统操作的功能

但是随着 python 的发展,越来越多面向对象的、更直观和易于使用的模块可以供大家使用

对于 os 模块,大家可以了解一下就行了

import os

print(os.getenv('PATH'))
# 获取环境变量PATH的值,并打印
# 示例输出:/home/martin/.local/bin:/usr/local/sbin:/usr/local/bin:...

print(os.uname())
# 获取操作系统的信息,并打印
# 示例输出:posix.uname_result(sysname='Linux', nodename='...', release='...', version='...', machine='x86_64')

print(os.times())
# 获取进程的CPU时间信息,并打印
# 示例输出:posix.times_result(user=0.01, system=0.0, children_user=0.0, children_system=0.0, elapsed=1740.63)

print(os.cpu_count())
# 获取可用的CPU核心数量,并打印
# 示例输出:16

print(os.getloadavg())
# 获取系统的平均负载,并打印
# 示例输出:(2.021484375, 2.35595703125, 2.04052734375)

old_umask = os.umask(0o022)
# 设置文件创建时的权限掩码,并将旧的掩码保存起来
# 在此处可以执行与文件相关的操作...

os.umask(old_umask)
# 恢复旧的文件权限掩码

sh 模块

sh 模块不是 python 的标准模块,它是一个第三方模块,在使用之前我们需要安装它

pip install sh
import sh

# 在 $PATH 中运行任何命令...
print(sh.ls('-la'))
# 执行ls命令并打印输出
# 示例输出:
# total 36
# drwxrwxr-x  2 martin martin  4096 apr  8 14:18 .
# drwxrwxr-x 41 martin martin 20480 apr  7 15:23 ..
# -rw-rw-r--  1 martin martin    30 apr  8 14:18 examples.py

ls_cmd = sh.Command('ls')
print(ls_cmd('-la'))  # 显式调用
# 使用Command对象执行ls命令并打印输出
# 示例输出与上述相同

# 如果命令不在PATH中:
custom_cmd = sh.Command('/path/to/my/cmd')
custom_cmd('some', 'args') # 执行自定义命令并传递参数


with sh.contrib.sudo:
    # 使用'sudo'执行一些操作...
    ...
# 使用'sudo'执行一些操作的上下文环境

当我们通过 sh 模块去执行一些 shell 命令时,sh 模块会尝试在本地环境变量($PATH)中查找带有该名称的内置 shell 命令或二进制文件

如果没有找到,可以自己添加命令路径

custom_cmd = sh.Command('/path/to/my/cmd')
custom_cmd('some', 'args')  # 执行自定义命令并传递参数

如果要将命令的输出写入到文件里面,可以使用 _out 参数

#相当于 ip address > /tmp/ipaddr
sh.ip.address(_out='/tmp/ipaddr')

我们在敲 shell 命令时通常会使用到管道符(|),在 sh 模块中通过 _in 参数来实现

print(sh.awk('{print $9}', _in=sh.ls('-la')))
# 等同于 "ls -la | awk '{print $9}'"

print(sh.wc('-l', _in=sh.ls('.', '-1')))
# 等同于  "ls -1 | wc -l"

对于异常处理,我们可以简单地处理 ErrorReturnCodeTimeoutException 异常

try:
    sh.cat('/tmp/doesnt/exist')
except sh.ErrorReturnCode as e:
    print(f'Command {e.full_cmd} exited with {e.exit_code}')
    # '/usr/bin/cat /tmp/doesnt/exist' 命令结果返回 1

curl = sh.curl('https://httpbin.org/delay/5', _bg=True)
try:
    curl.wait(timeout=3)
except sh.TimeoutException:
    print("Command timed out...")
    curl.kill()

标签:shell,模块,Python,命令,sh,file,print,new,os
From: https://www.cnblogs.com/edisonfish/p/17560956.html

相关文章

  • 命令_查看占用端口 netstat -ano|findstr "8080"
    查看占用端口 netstat-ano|findstr"8080" tasklist|findstr"12448"netstat-ano|findstr"8080"列说明1:协议 2:本地地址    3:外部地址   4:状态     5:PID查看PID对应的进程名称:tasklist|findstr"12448"......
  • python中的@classmethod和@staticmethod的作用
    classA(object):bar=1deffunc1(self):print("foo")@classmethoddeffunc2(cls):print("func2")print(cls.bar)cls().func1()A.func2()@classmethod的作用实际时可以在class内部实例化class。作用就是比u输......
  • python
    #不需要定义变量##while循环:#while条件:#xxx#xxx#for循环:#for临时变量in范围容器(可用range,如果是容器的话,就是遍历,如果in10,就是遍历0-10)#for循环的范围是大于等于第一个小于最后一个,也就是inti=0;i<n;i++#输入......
  • diff 和 patch 命令(打补丁)
    命令详解diff命令diff就是用在比对两个文件之间的差异的,并且是以行为单位来比对的!一般是用在ASCII纯文本文件的比对上。由于是以行为比对的单位,因此diff通常是用在同一的文件(或软件)的新旧版本差异上!”命令格式diff[OPTION]from-fileto-file>batch-filefrom-f......
  • python日志调试
    1.日志logging.debug():最低级别,用于小细节,通常用于在诊断问题时,才会关心谢谢消息logging.info():用于记录程序中一般事件的信息,或确认一切工作正常logging.warning():用于表示可能的问题,它不会阻止程序的工作,但将来可能会logging.error():用于记录错误,它导致程序做某事失败logg......
  • Cisco交换机常用命令
    Cisco交换机常用命令Cisco交换机常用模式进入特权模式S1>enable退出特权模式S1#disable进入全局配置模式S1#configureterminal进入接口配置模式S1(config)#interfacegigabitEthernet0/1退出接口配置模式S1(co......
  • python:基础语法(002)
    python的关键字:#打印python都有哪些关键字importkeywordprint(keyword.kwlist) 缩进:缩进快捷键Tab 多行语句:按回车键即可换行,用\反斜杠也可以换行 python的引号:python中可以使用单引号、双引号、三引号#单引号print('你好')#双引号print("你好")#三引......
  • Python学习——Day 7
    列表·列表需要使用中括号[],元素之间使用英文的逗号进行分隔·列表的创建方式      ·使用中括号      ·调用内置函数list()·列表的特点·列表元素的增加操作#向列表末尾添加一个元素lst=[10,20,30]print('添加元素之前',lst,id(lst))lst.appen......
  • jupyter Notebook:魔法命令
    JupyterNotebook是一个开源的交互式编程环境,用于创建和共享包含实时代码、文本、图像和可视化输出的文档。它交互式的编程方式是一大亮点,因为我们在数据分析的过程中,常常是一边分析,一边看分析结果,根据分析结果再调整数据或者分析参数。有了 JupyterNotebook,代码和运行结果可......
  • shell壳牌机油 摩托车使用感受
    就是这款5w-30(港版),a3/b4,粘度略微有点高了,11.8保护性强了,1500公里左右换下,机油并没有太脏的感觉,觉得可以2000+以上随便用。a3/b4认证的油踏板车是肯定能用的。事实证明确实很丝滑。......