LoginSignup
1
5

More than 5 years have passed since last update.

Python上でUNIXコマンドをたたきたいとき

Last updated at Posted at 2016-12-12

概要

MacのターミナルのコマンドをPythonで一括実行しようと思った人向け

環境

・Mac OS Sierra 10.12.1
・python 3.5.2

やり方

import subprocess
subprocess.call(["command"])

これだけ
※最初の記事では、書き方が間違っていました。
ShaderKidさんご指摘ありがとうございました!

使用例

import subprocess

# hello.txtを作成 中身は空
subprocess.call(["touch", "hello.txt"]) # --1

# hello.txtにhello world を書き込む
subprocess.call(["echo hello world > hello.txt"], shell = True) # --2

 書き方は2通りあって、上記の1の場合は、UNIXで空白とするところを「,」で区切る。
2つ目は、第1引数に文字列を与えて、shell=Trueとする。

 デフォルトではshell=Falseとなっており、公式でもTrueとすることはセキュリティ上の脅威となる、という記述があるため推奨されていない。
 ただ現時点では、2のようなコマンドを1の書き方で実行しようとすると、ターミナル上に文字が写されるだけなので、解消方法がわからない。

Error:Segmentation faultが出てきたとき

最初実行しようとしたらSegmentation faultというエラーメッセージが出てきた。
ググってもよくわからず、試しにpython3で実行したら動いた。python3を入れていたら、python3 index.pyみたいに打っても実行できるので、もし同じような現象になった方は実行してほしい。

参考

サブプロセス管理
Pythonでsubprocessを使ってコマンドを実行する方法

1
5
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
1
5