在python脚本中调用bash函数 [英] Call a bash function within a python script
问题描述
我有一个python
脚本(例如test.py
)和一个commands.txt
文件,其中包含一个自定义bash
函数(例如my_func
)以及其参数(例如
I have a python
script (e.g. test.py
) and a commands.txt
file which contains a custom bash
function (e.g. my_func
) along with its parameters, e.g.
my_func arg1 arv2; my_func arg3 arg4; my_func arg5 arg6;
此功能包含在~/.bash_profile
中.
我试图做的是:
This function is included in the ~/.bash_profile
.
What I have tried to do is:
subprocess.call(['.', path/to/commands.txt], shell=True)
就将shell参数设置为True而言,我知道这不是最好的情况,但是即使这样,我似乎也无法实现它.运行test.py
时得到的是:
my_func: command not found
I know this is not the best case, in terms of setting the shell argument into True, but I cannot seem to implement it even in this way. What I get when I run test.py
is:
my_func: command not found
推荐答案
您将需要直接调用bash,并指示其处理两个文件.
You will need to invoke bash directly, and instruct it to process both files.
在命令行上,这是:
bash -c '. ~/.bash_profile; . commands.txt'
用python包装它:
Wrapping it in python:
subprocess.call(['bash', '-c', '. ~/.bash_profile; . commands.txt'])
您也可以在commands.txt顶部找到〜/.bash_profile.这样您就可以运行一个文件.
You could also source ~/.bash_profile at the top of commands.txt. Then you'd be able to run a single file.
将函数提取到一个单独的文件中可能是有意义的,因为.bash_profile是供登录shell使用的,而不是这样.
It may make sense to extract the function to a separate file, since .bash_profile is intended to be used by login shells, not like this.
这篇关于在python脚本中调用bash函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!