簡體   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