2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonからコマンドを実行

Last updated at Posted at 2020-05-02

コード

import subprocess
import sys


def exec_cmd(cmd):
    # cmd文字列の前後にスペースが入っていたら削除 -> スペースで分割しlist化
    cmd_split = cmd.strip().split()
    # stdoutの設定で標準出力を取得
    cp = subprocess.run(cmd_split, stdout=subprocess.PIPE)
    # cp = subprocess.check_output(cmd_split)
    if cp.returncode != 0:
        print(f'{cmd_split[0]} faild.', file=sys.stderr)
        sys.exit(1)
    # 標準出力があれば返す
    if cp.stdout is not None:
        return cp.stdout

実行

コマンドを文字列でそのまま渡す

cmd = 'touch file.py'
exec_cmd(cmd)

リストの場合はスペース区切りでjoin()

files = ['file1.py', 'file2.py', 'file3.py', 'file4.py', 'file5.py']
files_sep_space = ' '.join(files)
cmd = f'touch {files_sep_space}'
exec_cmd(cmd)
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?