Ope*_*way 18 python bash interop language-interoperability
我正在写一个Python脚本,我的时间已经不多了.我需要做一些我在bash中非常熟悉的事情,所以我只是想知道如何将一些bash行嵌入到Python脚本中.
谢谢
Ian*_*ing 29
理想的方法:
def run_script(script, stdin=None):
"""Returns (stdout, stderr), raises error on non-zero return code"""
import subprocess
# Note: by using a list here (['bash', ...]) you avoid quoting issues, as the
# arguments are passed in exactly this order (spaces, quotes, and newlines won't
# cause problems):
proc = subprocess.Popen(['bash', '-c', script],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode:
raise ScriptException(proc.returncode, stdout, stderr, script)
return stdout, stderr
class ScriptException(Exception):
def __init__(self, returncode, stdout, stderr, script):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
Exception.__init__('Error in script')
Run Code Online (Sandbox Code Playgroud)
你也可以添加一个很好的__str__方法ScriptException(你肯定需要它来调试你的脚本) - 但我把它留给读者.
如果您不使用stdout=subprocess.PIPEetc,则脚本将直接附加到控制台.如果您有来自ssh的密码提示,这非常方便.因此,您可能希望添加标志来控制是否要捕获stdout,stderr和stdin.
假设主机系统支持该命令:
import os
os.system('command')
Run Code Online (Sandbox Code Playgroud)
如果你有一个很长的命令,或者一组命令。你可以使用变量。例如:
# this simple line will capture column five of file.log
# and then removed blanklines, and gives output in filtered_content.txt.
import os
filter = "cat file.log | awk '{print $5}'| sed '/^$/d' > filtered_content.txt"
os.system(filter)
Run Code Online (Sandbox Code Playgroud)
是
import os
os.system ("bash -c 'echo $0'")
Run Code Online (Sandbox Code Playgroud)
要为你做这件事吗?
编辑:关于可读性
是的,当然,你可以让它更具可读性
import os
script = """
echo $0
ls -l
echo done
"""
os.system("bash -c '%s'" % script)
Run Code Online (Sandbox Code Playgroud)
编辑2:关于宏,没有python到目前为止我不知道,但介于两者之间
import os
def sh(script):
os.system("bash -c '%s'" % script)
sh("echo $0")
sh("ls -l")
sh("echo done")
Run Code Online (Sandbox Code Playgroud)
和前面的例子一样,你基本上得到你想要的东西(但你必须允许一些辩证的限制)
| 归档时间: |
|
| 查看次数: |
38564 次 |
| 最近记录: |