22

Python スクリプトを書いていますが、時間がありません。私は bash でかなりよく知っているいくつかのことを行う必要があるので、Python スクリプトにいくつかの bash 行を埋め込むにはどうすればよいのでしょうか。

ありがとう

4

9 に答える 9

33

それを行うための理想的な方法:

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をキャプチャするかどうかを制御することができます。

于 2010-04-16T15:59:19.007 に答える
14

システムコマンドを呼び出す場合は、サブプロセスモジュールを使用します。

于 2010-04-16T09:49:17.163 に答える
6

コマンドがホスト システムでサポートされていると仮定します。

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)
于 2010-04-16T09:33:22.320 に答える
6

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")

前の例では、基本的に必要なものを取得します (ただし、弁証法上の制限を少し考慮する必要があります)。

于 2010-04-16T09:33:44.867 に答える
0

前述のように、os.system();を使用できます。速くて汚れていますが、使いやすく、ほとんどの場合に機能します。これは文字通り、C system()関数へのマッピングです。

http://docs.python.org/2/library/os.html#os.system

http://www.cplusplus.com/reference/cstdlib/system/

于 2013-03-22T01:14:30.377 に答える
0

There is also the commands module to give more control over the output: https://docs.python.org/2/library/commands.html

于 2010-04-16T10:31:49.247 に答える