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

前端 未结 5 706
轮回少年
轮回少年 2020-12-17 23:22

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

By doing

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


        
相关标签:
5条回答
  • 2020-12-18 00:06

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

    os.system('/bin/bash -c "echo hello world"')
    
    0 讨论(0)
  • 2020-12-18 00:16
    subprocess.Popen(cmd, shell=True, executable='/bin/bash')
    
    0 讨论(0)
  • 2020-12-18 00:16

    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
    
    0 讨论(0)
  • 2020-12-18 00:20

    I use this:

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

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

    0 讨论(0)
  • 2020-12-18 00:29

    Both commands are executed in different subshells.

    Setting variables in the first system call does not affect the second system call.

    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
    

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

    If you can use subprocess:

    >>> import subprocess
    >>> subprocess.call('/bin/bash -c "$GREPDB"', shell=True,
    ...                 env={'GREPDB': 'echo 123'})
    123
    0
    
    0 讨论(0)
提交回复
热议问题