简体   繁体   English

使用更改环境的命令在python中创建子进程Popen

[英]subprocess Popen in python with command that changes environment

I'm trying to run a python script from python using the subprocess module and executing a script sequentially. 我正在尝试使用子流程模块从python运行python脚本并按顺序执行脚本。 I'm trying to do this in UNIX but before I launch python in a new shell I need to execute a command (ppack_gnu) that sets the environment for python (and prints some lines in the console). 我试图在UNIX中执行此操作,但是在新外壳中启动python之前,我需要执行一个命令(ppack_gnu),该命令设置python的环境(并在控制台中打印一些行)。

The thing is that when I run this command from python subprocess the process hangs and waits for this command to finish whereas when I do it in the UNIX console it jumps to the next line automatically. 问题是,当我从python子进程运行此命令时,进程挂起并等待该命令完成,而当我在UNIX控制台中执行该命令时,它将自动跳至下一行。

Examples below: 下面的例子:

From UNIX: 从UNIX:

[user1@1:~]$ ppack_gnu; echo 1
You appear to be in prefix already (SHELL=/opt/soft/cdtng/tools/ppack_gnu/3.2/bin/bash)
1
[user1@1:~]$ 

From PYTHON: 从PYTHON:

processes.append(Popen("ppack_gnu; echo 1", shell=True, stdin = subprocess.PIPE))

This will print Entering Gentoo Prefix /opt/soft/cdtng/tools/ppack_gnu/3.2 - run 'bash -l' to source full bash profiles in the python console and then hang... 这将打印Entering Gentoo Prefix /opt/soft/cdtng/tools/ppack_gnu/3.2-运行'bash -l'在python控制台中获取完整的bash配置文件,然后挂起...

Popen() does not hang: it returns immediately while ppack_gnu may be still running in the background. Popen()不会挂起: ppack_gnu可能仍在后台运行时,它会立即返回。

The fact that you see the shell prompt does not mean that the command has returned: 您看到shell提示的事实并不意味着该命令已返回:

⟫ echo $$
9302 # current shell
⟫ bash
⟫ echo $$
12131 # child shell
⟫ exit
⟫ echo $$
9302 # current shell

( $$ -- PID of the current shell) $$ -当前外壳的PID)

Even in bash, you can't change environment variables of the parent shell (without gdb or similar hacks) that is why source command exists. 即使在bash中,您也不能更改父外壳的环境变量(没有gdb或类似的技巧),这就是source命令存在的原因。

stdin=PIPE suggests that you want to pass commands to the shell started by ppack_gnu . stdin=PIPE建议您将命令传递ppack_gnu开始的ppack_gnu Perhaps you need to add process.stdin.flush() after the corresponding process.stdin.write(b'command\\n') . 也许您需要在相应的process.stdin.write(b'command\\n')之后添加process.stdin.flush() process.stdin.write(b'command\\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM