LoginSignup
5
3

More than 5 years have passed since last update.

シェルで生成した外部入力をpythonスクリプトに読ませて実行する

Last updated at Posted at 2018-02-01

必要に迫られてあれこれ試行錯誤した結果,以下の方法でできるらしいことが判明.

Pythonコードの例

例として,読み込んだ外部入力の数字の2乗を返すコード:

example.py
print "input:"
i=raw_input(">> ")
i=float(i)
print i**2
quit()

シェルスクリプトの書き方

forで異なる外部変数を与えるようにしてみる:
※事前にexpectを

apt-get install expect

でインストールしておくこと.

test.sh
#/bin/sh
for itera 1 2 3 4 5
do
expect -c "
        set timeout -1
        spawn python example.py
        expect \">>\"
        send \"${itera}\n\"
        expect \"hoge\"
"
done

実行結果

あまり腑に落ちていないが,とりあえず上手くいっているようである.

spawn python example.py
input:
>> 1
1.0
spawn python example.py
input:
>> 2
4.0
spawn python example.py
input:
>> 3
9.0
spawn python example.py
input:
>> 4
16.0
spawn python example.py
input:
>> 5
25.0

コツとしては,シェルスクリプト内expectの中身の最後に

expect \"hoge\"

みたいな(一見意味のない)やつを噛ませると上手くいく.これが無いと何故か上手くいかなかった.

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