在Python子进程中运行连续的Shell命令

编程入门 行业动态 更新时间:2024-10-25 08:15:03
本文介绍了在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命令

本文发布于:2023-08-05 05:42:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1303022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进程   命令   Python   Shell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!