gpt4 book ai didi

python - 是否可以使用 python 的 shell 中定义的函数?

转载 作者:太空狗 更新时间:2023-10-29 21:36:42 26 4
gpt4 key购买 nike

例子:

#!/bin/bash

function my_test(){
echo this is a test $1
}

my_test 1

python -c "from subprocess import check_output; print(check_output('my_test 2', shell=True))"

输出:

this is a test 1
/bin/sh: my_test: command not found
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python3.5/subprocess.py", line 629, in check_output
**kwargs).stdout
File "/usr/lib/python3.5/subprocess.py", line 711, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command 'my_test 2' returned non-zero exit status 127

最佳答案

您需要导出 shell 函数,因此它将被子 shell 继承。

#!/bin/bash

function my_test(){
echo this is a test $1
}

my_test 1

export -f my_test
python -c "from subprocess import check_output; print(check_output('my_test 2', shell=True))"

关于python - 是否可以使用 python 的 shell 中定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com