'defining and running a shell function using python subprocess [duplicate]

I have a piece of python code that looks as following:

import subprocess

function = """my_function () \{
echo "test"
\}

"""
alias = 'alias my-function="my_function"'
command = "my-function"
process = subprocess.Popen([function,alias,command],
         stdout=subprocess.PIPE,
         stderr=subprocess.PIPE, shell = True)
stdout, stderr = process.communicate()
print(stderr.decode())

I would like to define my_function and call it using the command my-function

The abovementioned program prints out /bin/sh: 3: }: not found, meaning that it doesn't recognize the supplied closing bracket sign }. How can I properly define and call this function in this manner?



Solution 1:[1]

I think you want something like this:

import subprocess

function = 'my_function(){ echo test; }'
alias = 'alias myFunc=my_function'
cmd = 'myFunc'

# Make combined set of commands
commands = f'''
{function}
{alias}
{cmd}'''

# Run them
process = subprocess.check_output(commands,shell = True)

print(process)
b'test\n'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Setchell