2014-12-09 149 views
3

當我在交互模式下使用docker run時,我能夠運行我想測試一些python東西的命令。在Python子進程中在docker中運行交互命令

[email protected]:~# docker run -i -t dockerfile/python /bin/bash 
[ [email protected]:/data ]$ python -c "print 'hi there'" 
hi there 
[ [email protected]:/data ]$ exit 
exit 
[email protected]:~# 

我想用子模塊,所以我寫了蟒蛇自動化此此:

run_this = "print('hi')" 
random_name = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(20)) 
command = 'docker run -i -t --name="%s" dockerfile/python /bin/bash' % random_name 
subprocess.call([command],shell=True,stderr=subprocess.STDOUT) 
command = 'cat <<\'PYSTUFF\' | timeout 0.5 python | head -n 500000 \n%s\nPYSTUFF' % run_this 
output = subprocess.check_output([command],shell=True,stderr=subprocess.STDOUT) 
command = 'exit' 
subprocess.call([command],shell=True,stderr=subprocess.STDOUT) 
command = 'docker ps -a | grep "%s" | awk "{print $1}" | xargs --no-run-if-empty docker rm -f' % random_name 
subprocess.call([command],shell=True,stderr=subprocess.STDOUT) 

據說這是爲了創建容器,運行容器和出口蟒命令和刪除容器。它執行所有這些操作,除了命令在主機上運行而不是在Docker容器上運行。我猜Docker正在換殼或類似的東西。如何從新的shell運行python子進程?

回答

1

實際上,你需要生成的新的外殼你是opening.So一個新的子後docker creation運行docker enter或嘗試用pexpect代替subprocess.`pexpect產生一個新的孩子,這樣就可以發送指令相同的操作。

1

它看起來像你期待第二個命令cat <<...發送輸入到第一個命令。但是這兩個子進程命令沒有任何關係,所以這是行不通的。

Python的subprocess library和作爲其基礎的popen命令提供了一種方法來獲取管道到進程的stdin。這樣,你可以直接從Python發送你想要的命令,而不必試圖讓另一個子進程與它通信。

所以,像這樣:

from subprocess import Popen, PIPE 

p = Popen("docker run -i -t --name="%s" dockerfile/python /bin/bash", stdin=PIPE) 
p.communicate("timeout 0.5 python | head -n 500000 \n" % run_this) 

(我不是一個Python的專家,在道歉的錯誤串形成從this answer改編。)

相關問題