通过subprocess扩展Python语法以实现shell命令作为管道
项目描述
Python Shell Pipes
在Python中访问shell命令的简单方法
“shpipes”包使用“subprocess.Popen”在shell中轻松运行命令,从原生Python运行。
>>> from shpipes import Pipe
# python --version
>>> Pipe('python')('--version').getvalue()
'Python 3.8.6\n'
管道命令链
您可以链接您的命令,将一个命令的输出传递到另一个命令的输入,类似于shell管道。您可以使用按位包含或操作符将“Pipe”实例链接在一起。
# echo 1+1 | bc
>>> (Pipe('echo')('1+1') | Pipe('bc')).getvalue()
'2\n'
# This also works
>>> pipe = Pipe('echo')('1+1')
>>> pipe |= Pipe('bc'))
>>> pipe.getvalue()
'2\n'
从您的PATH变量加载命令
Shell Pipes还可以收集您的PATH变量中的所有可执行文件,并将它们收集到“Commands”实例中,这样您就可以像使用原生shell一样使用库。
>>> from shpipes import Commands
>>> shell = Commands()
# find . -type f | grep .py$ | wc -l
>>> (shell.find('.', '-type', 'f') | shell.grep('.py$') | shell.wc('-l')).getvalue()
'9\n'
# this also works
>>> pipe = shell.find('.', '-type', 'f')
>>> pipe |= shell.grep('.py$')
>>> pipe |= shell.wc('-l')
>>> pipe.getvalue()
'9\n'
处理管道参数
当调用“Pipe”时,其参数将直接传递到“Popen”,因此请注意字符串必须正确引用。您可以使用“getvalue)”从管道获取输出,然后将其作为命令参数而不是输入文本传递。只有当调用“getvalue)”时,管道才会被评估
>>> license = shell.find('.', '-name', '"LICENSE"').getvalue()
>>> shell.wc(license).getvalue()
' 21 169 1069 ./LICENSE\n'
默认为Shell
由于管道默认在shell中运行,因此环境变量会自动评估
>>> pipe = shell.ps('-u $USER')
>>> pipe |= shell.grep('python')
>>> pipe |= shell.head('-1')
配置选项
如果您需要运行不同的shell或完全禁用shell,则可以通过环境变量或kwargs传递给“Pipe”
在“Pipe”中覆盖选项
您可以通过传递参数给“Pipe”来覆盖所有“Popen”选项(除了“stdin”/“stdout”)。默认情况下,“Popen”以shell模式运行,使用您的默认shell。
>>> Pipe('ls', executable='/bin/zsh', cwd='/var', shell=False)
设置env SHPIPES_NO_SHELL=true
在调用“Popen”时设置shell=False
设置env SHPIPES_SHELL=/bin/zsh
更改“Popen”运行的可执行shell
项目详情
关闭
shell-pipes-0.1.0.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 58af2c90074fc8ec76a95f026c0d59f570a6226c2a551e7c4fe1fceaf2ad1198 |
|
MD5 | 7acaed47af40095bf1f17c51d7fc9023 |
|
BLAKE2b-256 | 2f3327e00c1fce243ee5ff623a4a15521b57e4d83952af668e8b434afc52979f |