使用子流程在Python中运行顺序命令 [英] Run sequential commands in Python with subprocess

查看:223
本文介绍了使用子流程在Python中运行顺序命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望可以为您提供帮助。我需要在Python脚本中运行带有特定映像的软件容器Docker(在我的情况下为Fenics),然后向他传递命令以执行脚本。

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.

我已经尝试过子进程:

   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())

但是它什么也没做。

推荐答案

在通话中删除 -it 标志可以做到 docker ,您不想要它们。另外,不要尝试通过stdin发送命令以将其执行到容器中,而只需传递命令以在您的调用中运行 docker exec

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.

我没有运行容器,所以我将使用 docker run ,但是下面的代码应该为您提供线索:

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)

这将在 python -c print( hello)中运行容器并捕获输出,因此Python(3.6)脚本将自己打印

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\n'

它在Python 2.7中也可以使用,我不知道您在主机上使用的是哪个版本:)

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

关于与子流程进行通信,请参见官方文档子进程。Popen.communicate。从Python 3.5开始,还有 subprocess.run ,生活更加轻松。

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!

这篇关于使用子流程在Python中运行顺序命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆