Home > Software engineering >  Execute multiline bash command from Python and get its output
Execute multiline bash command from Python and get its output

Time:02-13

I am under Python 3.8.10 in Ubuntu 20.04 trying to execute a multiline bash command and get its output. For this I am trying to combine this and this. My bash command is this:

/home/foo/.drsosc/drs-5.0.6/drscl << ASD      
info
exit
ASD

and it works as I want. Now in Python I have this:

from pathlib import Path
import subprocess

PATH_TO_drscl = Path.home()/Path('.drsosc/drs-5.0.6/drscl')

def send_command(cmd: str):
    execute_this = f'''{PATH_TO_drscl} << ASD
{cmd}
exit
ASD'''
    return subprocess.run([execute_this], stdout=subprocess.PIPE)

print(send_command('info'))

but I get

FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.drsosc/drs-5.0.6/drscl << ASD\ninfo\nexit\nASD'

It seems that the problem is with the '\n' not being properly interpreted?

CodePudding user response:

No, the problem is that you're trying to run small shell script but you're calling an executable that has a name composed of all commands in the script. Try with shell=True:

return subprocess.run([execute_this], stdout=subprocess.PIPE, shell=True)

CodePudding user response:

I found that this works as I want:

result = subprocess.run(
    str(PATH_TO_drscl), 
    input = f'{cmd}\nexit',
    text = True, 
    stdout = subprocess.PIPE
)
  • Related