使用python子流程定义并运行shell函数



我有一段python代码,如下所示:

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())

我想定义my_function并使用命令my-function调用它

上述程序打印出/bin/sh: 3: }: not found,这意味着它无法识别所提供的闭合括号符号}。如何以这种方式正确定义和调用此函数?

我想你想要这样的东西:

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'testn'

最新更新