python中and与or的执行顺序-使用子流程在Python中运行顺序命令

1586010002-jmsa.png

hope you can help. I need, in my Python script, to run the software container Docker with a specific image (Fenics in my case) and then to pass him a command to execute a script.

I've tried with subprocess:

cmd1 = 'docker exec -ti -u fenics name_of_my_container /bin/bash -l'

cmd2 = 'python2 shared/script_to_be_executed.py'

process = subprocess.Popen(shlex.split(cmd1),

stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr =

subprocess.PIPE)

process.stdin.write(cmd2)

print(first_process.stdout.read())

But it doesn't do anything. Suggestions?

解决方案

Drop the -it flags in your call do docker, you don't want them. Also, don't try to send the command to execute into the container via stdin, but just pass the command to run in your call do docker exec.

I don't have a container running, so I'll use docker run instead, but the code below should give you a clue:

import subprocess

cmd = 'docker run python:3.6.4-jessie python -c print("hello")'.split()

p = subprocess.Popen(cmd, stdout=subprocess.PIPE)

out, err = p.communicate()

print(out)

This will run python -c print("hello") in the container and capture the output, so the Python (3.6) script will itself print

b'hello '

It will also work in Python 2.7, I don't know which version you're using on the host machine :)

Regarding communicating with a subprocess, see the official docs subprocess.Popen.communicate. Since Python 3.5 there's also subprocess.run, which makes your life even easier.

HTH!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值