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

ore*_*isf 7 python shell subprocess

例:

#!/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))"
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 9

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

#!/bin/sh

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))"
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用例如`bash -a my_script`运行脚本,则shell会标记要导出的所有名称和函数,而不必修改脚本本身. (2认同)