正在从 python 脚本执行 bash 配置文件别名

Executing bash profile aliases from python script

我知道这里已经发布了许多类似的问题,但是其中 none 似乎适用于我的情况。我的 bash 配置文件中有一些命令,如下所示

export HEADAS=/Users/heasoft/x86_64-apple-darwin18.7.0
alias heainit=". $HEADAS/headas-init.sh"
. $HEADAS/headas-init.sh

export SAS_DIR=/Users/sas-Darwin-16.7.0-64/xmmsas
alias sas=". $SAS_DIR/setsas.sh"

sit='source ~/.bash_profile'

我在其中连续为 运行 它们创建了一个别名:alias prep1='sit; heainit; sas。当我在命令行中执行它时,它工作得很好。但我想插入 python 脚本并从那里插入 运行。我是 运行宁 Python (v 3.7.4)。所以,按照 中的建议,我尝试了

import subprocess

command = "prep1"
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
output = process.communicate()   
print(output[0].decode())

但是我收到一条错误消息,提示未找到命令。我尝试将其导出到 bash 配置文件中,但出现错误 -bash: export: prep1: not a function

我也尝试了here中建议的方法,但还是不行。与此相关,我什至无法 运行 shell 命令,如下面的 python

epatplot set=evli.FTZ plotfile="pn_filtered_pat.ps" 2>&1 | tee pn_filtered_pat.txt

这是我的Python脚本尝试

command = "epatplot set=evli.FTZ plotfile="pn_filtered_pat.ps" 2>&1 | tee pn_filtered_pat.txt"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()

我得到 SyntaxError: invalid syntax。我知道这个语法错误是从哪里来的,但不知道如何解决。

我是 python 的初学者,所以我很感激 help/guidance。

请看这个回答:https://askubuntu.com/a/98791/1100014

建议将您的别名转换为 bash 函数,然后使用 -f 导出它们以便在子 shell 中可用。

调用Popen时,执行"bash -c <functionname>".

至于你上次的脚本尝试,引号有冲突。用这样的单引号替换外部引号:

command = 'epatplot set=evli.FTZ plotfile="pn_filtered_pat.ps" 2>&1 | tee pn_filtered_pat.txt'
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()