Python スクリプトを書いていますが、時間がありません。私は bash でかなりよく知っているいくつかのことを行う必要があるので、Python スクリプトにいくつかの bash 行を埋め込むにはどうすればよいのでしょうか。
ありがとう
Python スクリプトを書いていますが、時間がありません。私は bash でかなりよく知っているいくつかのことを行う必要があるので、Python スクリプトにいくつかの bash 行を埋め込むにはどうすればよいのでしょうか。
ありがとう
それを行うための理想的な方法:
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')
に素敵な__str__
メソッドを追加することもできScriptException
ます(スクリプトをデバッグするために必ず必要です)-しかし、私はそれを読者に任せます。
etcを使用しない場合stdout=subprocess.PIPE
、スクリプトはコンソールに直接添付されます。これは、たとえば、sshからのパスワードプロンプトがある場合に非常に便利です。したがって、フラグを追加して、stdout、stderr、およびstdinをキャプチャするかどうかを制御することができます。
システムコマンドを呼び出す場合は、サブプロセスモジュールを使用します。
コマンドがホスト システムでサポートされていると仮定します。
import os
os.system('command')
長いコマンドまたは一連のコマンドがある場合。変数を使用できます。例えば:
# 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)
は
import os
os.system ("bash -c 'echo $0'")
あなたのためにそれをするつもりですか?
編集:読みやすさについて
はい、もちろん、もっと読みやすくすることができます
import os
script = """
echo $0
ls -l
echo done
"""
os.system("bash -c '%s'" % script)
EDIT2:マクロに関しては、私が知る限り、Pythonはこれまでのところ行きませんが、
import os
def sh(script):
os.system("bash -c '%s'" % script)
sh("echo $0")
sh("ls -l")
sh("echo done")
前の例では、基本的に必要なものを取得します (ただし、弁証法上の制限を少し考慮する必要があります)。
前述のように、os.system();を使用できます。速くて汚れていますが、使いやすく、ほとんどの場合に機能します。これは文字通り、C system()関数へのマッピングです。
There is also the commands
module to give more control over the output:
https://docs.python.org/2/library/commands.html