目录
一、sh是什么
二、使用步骤
1.安装
2.使用示例
3.使用sh执行命令
4.关键字参数
5.查找命令
6.Baking参数
首页 后端开发 Python教程 Python之shell脚本怎么使用

Python之shell脚本怎么使用

May 11, 2023 am 10:25 AM
python shell

一、sh是什么

SH是一个独特的子进程包装器,可将您的系统程序动态映射到Python函数。SH帮助您用Python编写Shell脚本,既能支持Bash的所有功能(简单的命令调用,简单的管道传输) ,又能兼顾Python的灵活性。

SH是Python中成熟的子进程接口,允许您调用任何系统程序,就好像它是一个函数一样。也就是说,SH让您几乎可以调用任何可以从登录shell运行的命令。

更重要的是,您可以更轻松地捕获和解析命令的输出。

二、使用步骤

1.安装

通过pip命令来安装sh

pip install sh

2.使用示例

启动和运行的最简单方法是直接导入sh或从sh导入您需要的命令。然后,该命令就可以像Python函数一样使用。

比如,传递参数,捕获输出并在python中使用输出。详见下面的代码示例

# get interface information
import sh
print sh.ifconfig("eth0")

from sh import ifconfig
print ifconfig("eth0")

# print the contents of this directory
print ls("-l")

# substitute the dash for an underscore for commands that have dashes in their names
sh.google_chrome("http://google.com")

子命令的两种写入方式

# 子命令
>>> from sh import git, sudo
>>> print(git.branch("-v"))
>>> print(git("branch", "-v"))
>>> print(sudo.ls("/root"))
>>> print(sudo("/bin/ls", "/root"))

# with 环境
>>> with sh.contrib.sudo(_with=True):
        print(ls("/root"))
# _with=True 关键字告诉命令它正处于 with 环境中, 以便可以正确地运行.

#将多个参数传递给命令时,每个参数必须是一个单独的字符串:

from sh import tar
tar("cvf", "/tmp/test.tar", "/my/home/directory/")
# 这将不起作用:

from sh import tar
tar("cvf /tmp/test.tar /my/home/directory")

3.使用sh执行命令

命令的调用就像函数一样。

但是“需要注意的是,这些不是真正的Python函数,实际运行的是系统中对应的二进制命令,就像Bash一样,通过解析PATH在系统上动态地运行。

也正因为这样,Python对Shell命令的支持非常好,系统上所有命令都可以通过Python轻松运行。”

许多程序都有自己的命令子集,例如git(分支,签出)。

sh通过属性访问处理子命令。

from sh import git

# resolves to "git branch -v"
print(git.branch("-v"))

print(git("branch", "-v")) # the same command

4.关键字参数

关键字参数也可以像您期望的那样工作:它们被替换为命令行参数选项。

# Resolves to "curl http://duckduckgo.com/ -o page.html --silent"
sh.curl("http://duckduckgo.com/", o="page.html", silent=True)

# If you prefer not to use keyword arguments, this does the same thing
sh.curl("http://duckduckgo.com/", "-o", "page.html", "--silent")

# Resolves to "adduser amoffat --system --shell=/bin/bash --no-create-home"
sh.adduser("amoffat", system=True, shell="/bin/bash", no_create_home=True)

# or
sh.adduser("amoffat", "--system", "--shell", "/bin/bash", "--no-create-home")

5.查找命令

“Which”查找程序的完整路径,如果不存在,则返回None。 该命令是用Python函数真正实现的少数命令之一,因此不依赖于实际存在的”which”二进制程序。

print sh.which("python")     # "/usr/bin/python"
print sh.which("ls")         # "/bin/ls"

if not sh.which("supervisorctl"): sh.apt_get("install", "supervisor", "-y")

sh还可以使用更多功能,并且可以找到所有功能。 在里面官方文件。

6.Baking参数

sh可以将”baking”参数用作命令,作用是输出对应的完整命令行字符串,如下面的代码所示:

# The idea here is that now every call to ls will have the “-la” arguments already specified.
from sh import ls

ls = ls.bake("-la")
print(ls) # "/usr/bin/ls -la"

# resolves to "ls -la /"
print(ls("/"))

ssh+baking命令

在命令上调用”bake”会创建一个可调用对象,该对象会自动传递所有传递给”bake”的参数。

# Without baking, calling uptime on a server would be a lot to type out:
serverX = ssh("myserver.com", "-p 1393", "whoami")

# To bake the common parameters into the ssh command
myserver = sh.ssh.bake("myserver.com", p=1393)

print(myserver) # "/usr/bin/ssh myserver.com -p 1393"

现在,可调用“myserver”表示一个baking的ssh命令:

# resolves to "/usr/bin/ssh myserver.com -p 1393 tail /var/log/dumb_daemon.log -n 100"
print(myserver.tail("/var/log/dumb_daemon.log", n=100))

# check the uptime
print myserver.uptime()
 15:09:03 up 61 days, 22:56,  0 users,  load average: 0.12, 0.13, 0.05

以上是Python之shell脚本怎么使用的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Laravel 教程
1604
29
PHP教程
1510
276
如何在Python中创建虚拟环境 如何在Python中创建虚拟环境 Aug 05, 2025 pm 01:05 PM

创建Python虚拟环境可使用venv模块,步骤为:1.进入项目目录执行python-mvenvenv创建环境;2.Mac/Linux用sourceenv/bin/activate、Windows用env\Scripts\activate激活;3.使用pipinstall安装包、pipfreeze>requirements.txt导出依赖;4.注意避免将虚拟环境提交到Git,并确认安装时处于正确环境。虚拟环境能隔离项目依赖防止冲突,尤其适合多项目开发,编辑器如PyCharm或VSCode也

Python时间表库示例 Python时间表库示例 Aug 04, 2025 am 10:33 AM

使用Pythonschedule库可轻松实现定时任务,首先通过pipinstallschedule安装库,接着导入schedule和time模块,定义需要定时执行的函数,然后使用schedule.every()设置时间间隔并绑定任务函数,最后通过while循环中调用schedule.run_pending()和time.sleep(1)持续运行任务;例如每10秒执行一次任务可写为schedule.every(10).seconds.do(job),支持按分钟、小时、天、周等周期调度,也可指定具体

如何在崇高文本中运行Python代码 如何在崇高文本中运行Python代码 Aug 04, 2025 pm 04:25 PM

EnsurePythonisinstalledandaddedtoPATHbycheckingversioninterminal;2.Savefilewith.pyextension;3.UseCtrl Btorunviadefaultbuildsystem;4.CreateacustombuildsystemifneededbygoingtoTools>BuildSystem>NewBuildSystem,enteringthecorrectcmdforyourPythonvers

在Python中调试内存泄漏的常见策略是什么? 在Python中调试内存泄漏的常见策略是什么? Aug 06, 2025 pm 01:43 PM

Usetracemalloctotrackmemoryallocationsandidentifyhigh-memorylines;2.Monitorobjectcountswithgcandobjgraphtodetectgrowingobjecttypes;3.Inspectreferencecyclesandlong-livedreferencesusingobjgraph.show_backrefsandcheckforuncollectedcycles;4.Usememory_prof

Python的生存分析 Python的生存分析 Aug 03, 2025 pm 12:58 PM

生存分析用于研究事件发生的时间,Python中常用lifelines和scikit-survival实现。1.安装lifelines库并准备包含时间与事件状态的数据;2.使用Kaplan-Meier估计器绘制生存曲线以可视化事件未发生的概率;3.通过Cox比例风险模型分析变量对事件时间的影响,并检查模型假设;4.注意删失数据的处理,确保event列正确标记删失与事件发生。

如何与Python的时区合作? 如何与Python的时区合作? Aug 05, 2025 pm 04:53 PM

use usezoneInInfoforpython3.9 toCreateTimeZone-wardEteTimesandConvertBetBetWeenTimeZonesWithAstimeZone(); 2.Forpython3.6–3.6-3.6-3.6,useppypytzwithlocalize()

Java vs Python用于后端开发:详细比较 Java vs Python用于后端开发:详细比较 Aug 04, 2025 am 11:57 AM

性能要求高的系统如金融交易选Java,轻量级服务选Python;2.Python开发效率高适合MVP,Java适合大型团队协作;3.Java企业级生态成熟,Python框架轻便尤其FastAPI表现突出;4.高并发分布式系统首选Java,Python需异步模型提升性能;5.Python学习曲线平缓人才广泛,Java企业级人才储备充足;6.Python适合云原生轻量部署,Java在传统运维中更稳定;最终选择应结合团队技术栈、项目周期、性能需求、集成复杂度和运维成本综合判断,关键是用对场景。

Python烧瓶蓝图示例 Python烧瓶蓝图示例 Aug 05, 2025 am 01:44 AM

使用FlaskBlueprint可以将应用按功能模块化;1.创建蓝图实例并定义路由,如user.py中创建user_bp;2.在另一文件如post.py中创建其他蓝图;3.在app.py中导入并用app.register_blueprint()注册各蓝图;4.运行后访问对应URL即可看到模块化后的路由效果,代码结构更清晰且易于维护。

See all articles