如何强制 os.system() 使用 bash 而不是 shell

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21822054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:35:41  来源:igfitidea点击:

How to force os.system() to use bash instead of shell

pythonbashpython-2.4

提问by sunshinekitty

I've tried what's told in How to force /bin/bash interpreter for oneliners

我已经尝试过如何为 oneliners 强制 /bin/bash 解释器中所说的

By doing

通过做

os.system('GREPDB="my command"')
os.system('/bin/bash -c \'$GREPDB\'')

However no luck, unfortunately I need to run this command with bash and subp isn't an option in this environment, I'm limited to python 2.4. Any suggestions to get me in the right direction?

但是没有运气,不幸的是我需要用 bash 运行这个命令,而 subp 在这个环境中不是一个选项,我仅限于 python 2.4。有什么建议可以让我朝着正确的方向前进?

回答by falsetru

Both commands are executed in different subshells.

这两个命令都在不同的子 shell 中执行。

Setting variables in the first systemcall does not affect the second systemcall.

在第一次system调用中设置变量不会影响第二次system调用。

You need to put two command in one string (combining them with ;).

您需要将两个命令放入一个字符串中(将它们与 组合;)。

>>> import os
>>> os.system('GREPDB="echo 123"; /bin/bash -c "$GREPDB"')
123
0

NOTEYou need to use "$GREPDB"instead of '$GREPDBS'. Otherwise it is interpreted literally instead of being expanded.

注意您需要使用"$GREPDB"而不是'$GREPDBS'. 否则,它会按字面解释而不是被扩展。

If you can use subprocess:

如果您可以使用subprocess

>>> import subprocess
>>> subprocess.call('/bin/bash -c "$GREPDB"', shell=True,
...                 env={'GREPDB': 'echo 123'})
123
0

回答by mgoldwasser

The solution below still initially invokes a shell, but it switches to bash for the command you are trying to execute:

下面的解决方案最初仍会调用 shell,但它会为您尝试执行的命令切换到 bash:

os.system('/bin/bash -c "echo hello world"')

回答by Chunlin Zhang

I use this:

我用这个:

subprocess.call(["bash","-c",cmd])

//OK, ignore this because I have not notice subprocess not considered.

//好的,忽略这个,因为我没有注意到没有考虑子进程。

回答by Sarvar Nishonboev

I searched this command for some days and found really working code:

我搜索了这个命令几天,发现了真正有效的代码:

import subprocess

def bash_command(cmd):
    subprocess.Popen(['/bin/bash', '-c', cmd])

code="abcde"
// you can use echo options such as -e
bash_command('echo -ne "'+code+'"')

Output:

输出:

abcde

回答by Rufus

subprocess.Popen(cmd, shell=True, executable='/bin/bash')