使用Python打开一个shell环境,运行一个命令并退出环境 [英] Using Python to open a shell environment, run a command and exit environment

查看:2096
本文介绍了使用Python打开一个shell环境,运行一个命令并退出环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图自动化使用python的过程。如果我只是在终端工作流程是这样的:

 用户:> 。 /path/to/env1.sh
用户:>蟒蛇something.py
用户:>出口
用户:> 。 /path/to/env2.sh
用户:>蟒蛇something2.py
用户:>出口

等,为几个步骤。每个 env.sh 产生一个新的脚本环境变量的整体转换,并在当前目录中诸如此类的设定。我是pretty知道我需要使用子,但我不完全知道如何去做。理想情况下,工作流程会去:打开新的shell - >运行某些命令 - >退出外壳 - >根据需要重复

编辑:看来需要一些澄清。我知道如何使用 subprocess.Popen() subprocess.call()从shell中调用的东西, Python脚本从调用。这不是我所需要的。当一个叫 env.sh 它设置一个整体每吨环境变量和其他一些相关的东西,然后滴你进入一个shell来运行命令。要注意的是 env.sh 不会终止,直到一个类型退出运行所需的命令后。使用 subprocess.call(./ env.sh,壳=真)打开外壳和停在那里。它就像输入命令 ./ env.sh 除了当一个人发出退出命令,其余Python脚本。所以:

  subprocess.call(/path/to/env.sh,壳=真)
subprocess.call(蟒蛇something.py,壳=真)

没有做什么,我需要它做的事,也没有:

  P = subprocess.Popen(/path/to/env.sh,壳=真)
subprocess.call(蟒蛇something.py,壳=真)
p.kill()


解决方案

据我了解,你想运行一个命令,然后将它传递其他命令:

 从子进口POPEN,PIPEP = POPEN(/路径/要/ env.sh,标准输入= PIPE)#设定环境,开始新的shell
p.communicate(蟒蛇something.py \\ n退出)#通过命令来打开外壳

I'm trying to automate a process using python. If I am just in the terminal the workflow looks like:

user:> . /path/to/env1.sh
user:> python something.py
user:> exit
user:> . /path/to/env2.sh
user:> python something2.py
user:> exit 

etc for a few more steps. Each env.sh spawns a new script with a whole slew of environment variables and whatnot set within the current directory. I'm pretty sure I need to use subprocess, but I'm not exactly sure how to go about it. Ideally the workflow would go: open new shell --> run some commands --> exit shell --> repeat as necessary.

EDIT: It seems some clarification is needed. I understand how to use subprocess.Popen() and subprocess.call() to call things from within the shell that the Python script was called from. This is not what I need. When one calls env.sh it sets a whole ton of environment variables and a few other pertinent things and then drops you into a shell to run commands. It is important to note env.sh does not terminate until one types exit after running desired commands. Using subprocess.call("./env.sh", shell = True) opens the shell and stops there. It is just like entering the command ./env.sh except that when one issues the exit command, the rest of the python script. So:

subprocess.call(". /path/to/env.sh", shell = True)
subprocess.call("python something.py", shell = True)

Does NOT do what I need it to do, nor does:

p = subprocess.Popen(". /path/to/env.sh", shell = True)
subprocess.call("python something.py", shell = True)
p.kill()

解决方案

As I understand you want to run a command and then pass it other commands:

from subprocess import Popen, PIPE

p = Popen("/path/to/env.sh", stdin=PIPE)   # set environment, start new shell
p.communicate("python something.py\nexit") # pass commands to the opened shell

这篇关于使用Python打开一个shell环境,运行一个命令并退出环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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