[Python] Python subprocess with long bash scripts

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    Im using this code to run some bash commands using Python script:

    cmd = 'findmnt --kernel /tmp | grep nosuid 2>/dev/null'

    Sbp = subprocess.call(cmd ,
    shell=True,
    executable="/bin/bash",
    text=True)


    That works fine, but sometimes I need to execute some complex commands like these:

    grep -Eis "(\\\v|\\\r|\\\m|\\\s|$(grep \'^ID=\' /etc/os-release | cut -d= -f2 | sed -e \'s/\"//g\'))\" /etc/motd 2>/dev/null


    How can I assign these complex commands to the variable with these spaces and characters?

    I'm trying to find some PowerShell Here-string or ScriptBlock analog. Example in Powershell:

    $cmd = @'
    grep -Eis "(\\\v|\\\r|\\\m|\\\s|$(grep \'^ID=\' /etc/os-release | cut -d= -f2 | sed -e \'s/\"//g\'))\" /etc/motd 2>/dev/null
    '@


    or

    $ScriptBlock = {grep -Eis "(\\\v|\\\r|\\\m|\\\s|$(grep \'^ID=\' /etc/os-release | cut -d= -f2 | sed -e \'s/\"//g\'))\" /etc/motd 2>/dev/null}


    What is the best and simple way to understand this with examples in Python?

    Continue reading...

Compartilhe esta Página