繁体   English   中英

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

[英]Executing bash profile aliases from python script

我知道这里已经发布了许多类似的问题,但它们似乎都不适用于我的情况 我的 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 alias prep1='sit; heainit; sas 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

我也尝试了这里建议的方法,但仍然没有。 与此相关,我什至无法在 python 中运行 shell 命令,如下所示

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 的初学者,所以我感谢任何帮助/指导。

请看这个答案: 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM