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

标签 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))"

输出:

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/

相关文章:

shell - 如何创建一个 unix 脚本来通过将表名作为文件的输入来循环 Hive SELECT 查询?

linux - 如何排队多个程序顺序运行?

Python创建一个子进程并且不等待

python - 需要一个 python 模块来提取文本文档

python - Elasticsearch脚本使用densed_vector查询余弦相似度给出 “class_cast_exception”错误

Python:查找视频中的笔迹数量

bash - 继续从 tcp 服务器读取数据,直到收到特定消息

python - subprocess.check_output() 有问题

python - 通过 Python 子进程模块在 shell 中进行管道传输

python - Flask 的上下文堆栈的目的是什么?