python - python 脚本可以在 bash 脚本中执行函数吗?

标签 python bash

我有一个由第 3 方提供的 bash 脚本,它定义了一组函数。这是一个看起来像的模板

$ cat test.sh

#!/bin/bash

define go() {
    echo "hello"
}

我可以从 bash shell 执行以下操作来调用 go():

$ source test.sh
$ go
hello

有没有办法从 python 脚本访问相同的函数?我尝试了以下方法,但没有成功:

Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call("source test.sh")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/subprocess.py", line 470, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.6/subprocess.py", line 623, in __init__
    errread, errwrite)
  File "/usr/lib/python2.6/subprocess.py", line 1141, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
>>> 

最佳答案

是的,间接的。鉴于此 foo.sh:

function go() { 
    echo "hi" 
}

试试这个:

>>> subprocess.Popen(['bash', '-c', '. foo.sh; go'])

输出:

hi

关于python - python 脚本可以在 bash 脚本中执行函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5826427/

相关文章:

python - AttributeError at/accounts/login/'dict' 对象没有属性 'status_code'

python.data.ops.dataset_ops.BatchDataset - 如何使用它来创建训练和测试数据集

bash - HDFS 上的 Snappy 压缩文件没有扩展名且不可读

python - 使用特定的 SVN 修订版时,PIP 总是重新安装包

python - 使用 pandas 绘制 Bokeh 线图的问题

python - 如何在没有 pythonw.exe 的情况下将 Python 脚本放在后台?

linux - bash 内置时间命令的精度是多少?

linux - 什么都没有改变时的rsync inode差异

regex - 在 Bash 中使用逗号分隔的字符串作为变量的输入

linux - 令人困惑的 shell 语法