python shell常用命令,使用Python打开一个shell环境,运行一个命令并退出环境

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值