在Python子进程中运行连续的Shell命令 [英] Run consecutive Shell commands in Python-Subprocess

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

问题描述

这些是我要运行的一些相关命令.我的期望是它将当前文件夹更改为 abc &列出文件.

These are some dependant commands i am trying to run. My expectation was it will change current folder to abc & list files.

还设置 z = 88 后,它将打印 z .

import subprocess
cmd_list = []
cmd_list.append("cd ./abc")
cmd_list.append("ls")
cmd_list.append("export z=88")
cmd_list.append("echo $z")

my_env = os.environ.copy()
for cmd in cmd_list:
    sp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env, shell=True,text=True)

但是无法获得 ls echo $ z

推荐答案

您不能通过多次调用 subprocess.Popen()来做到这一点.每次调用都会创建一个新的子进程,并且它们对环境所做的更改不会传播回Python进程.

You can't do this with multiple calls to subprocess.Popen(). Each call creates a new child process, and changes they make to their environment do not propagate back to the Python process.

您可以通过将所有命令连接到一个命令行中来进行操作,该命令行由 bash -c 运行.

You can do it by concatenating all the commands into a single command line to be run by bash -c.

cmd = 'cd abc; ls; export z=88; echo $z'
subprocess.Popen(['bash', '-c', cmd], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env,text=True)

导出 z 也没有意义,因为您没有运行使用该环境变量的Shell的任何子进程.只需使用 z = 88 分配一个普通的shell变量即可.

There's also no point in exporting z, since you're not running any child processes of the shell that use the environment variable. Just assign an ordinary shell variable with z=88.

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

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