LoginSignup
3
2

More than 5 years have passed since last update.

Pythonでシェルコマンド実行

Posted at

subprocessを使う

  • 下記で ' ls -l 'が実行できます。
import subprocess

cmd = 'ls -l'
print(subprocess.check_call(cmd.split()))

他の例

  • mv とかで 「引数リストが多すぎます」のエラーが出た時の対処
    • xargsを使えばシェルで対応できるけど、シェルに慣れてない人はこっちの書き方のほうがわかりやすいはず...
import os
import subprocess

d = os.listdir('./dir')

for dd in d:
    cmd = 'mv ./dir/' + dd + ' ./dir_new/'
    subprocess.check_call(cmd.split())

3
2
2

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
3
2