我试图通过将python变量导出到shell脚本而不是直接从用户读取它来从python运行shell脚本。之前成功回答了关于passing array values as variable to shell script的问题并帮助我将数组中的值作为输入变量传递给shell脚本。我想从以下python脚本中导出多个变量,例如FLUID
,TTYPE
和FLIBRARY
:
FLUID="MDM"
TTYPE=0
FLIBRARY="RefProp"
HSPACE=[0.01, 0.009, 0.008, 0.007]
subprocess.call(['./testfile1'] + [str(n) for n in HSPACE])
到以下名为testfile1的shell脚本:
#!/bin/bash
echo "$FLUID, $FLIBRARY" | ./vls.exe
for i; do
awk 'NR==8 {$1=" " a }1' a=$i spacingcontrol.vls > tmp.vls && mv tmp.vls spacingcontrol.vls
awk 'NR==8 {$2=" " b " "}1' b=$i spacingcontrol.vls > tmp.vls && mv tmp.vls spacingcontrol.vls
done
答案 0 :(得分:1)
您可以在Python脚本中将它们设置为环境变量:
import os
import subprocess
os.environ['FLUID'] ="MDM"
os.environ['TTYPE'] = str(0)
os.environ['FLIBRARY'] = "RefProp"
HSPACE=[0.01, 0.009, 0.008, 0.007]
subprocess.call(['./testfile1'] + [str(n) for n in HSPACE])
答案 1 :(得分:0)
您可以选择将变量作为参数传递吗?
subprocess.call(['./testfile1 %s %s' % (FLUID, FLIBRARY)] + [str(n) for n in HSPACE])
并在bash脚本中
#!/bin/bash
FLUID=$1
FLIBRARY=$2
echo "$FLUID, $FLIBRARY" | ./vls.exe
答案 2 :(得分:0)
#!/usr/bin/env python
import subprocess
FLUID="MDM"
TTYPE=0
FLIBRARY="RefProp"
HSPACE=[0.01, 0.009, 0.008, 0.007]
subprocess.call(['./testfile1'] + [str(n) for n in HSPACE],
env={'fluid': FLUID, 'ttype': str(TTYPE), 'flibrary': FLIBRARY})
...此后,在shell中:
#!/bin/bash
hspace=( "$@" )
declare -p fluid ttype flibrary hspace # print values
...输出为:
declare -x fluid="MDM"
declare -x ttype="0"
declare -x flibrary="RefProp"
declare -a hspace='([0]="0.01" [1]="0.009" [2]="0.008" [3]="0.007")'
另一种方法是使用位置参数。
#!/usr/bin/env python
import subprocess
FLUID="MDM"
TTYPE=0
FLIBRARY="RefProp"
HSPACE=[0.01, 0.009, 0.008, 0.007]
subprocess.call(['./testfile1', str(FLUID), str(TTYPE), str(FLIBRARY)] + [str(n) for n in HSPACE])
...而且,在shell中:
#!/bin/bash
fluid=$1; shift
ttype=$2; shift
flibrary=$3; shift
hspace=( "$@" )
declare -p fluid ttype flibrary hspace # print values
...输出为:
declare -- fluid="MDM"
declare -- ttype="RefProp"
declare -- flibrary="0.009"
declare -a hspace='([0]="0.01" [1]="0.009" [2]="0.008" [3]="0.007")'
注意:
awk -v var="$val"
是将变量值从bash传递到awk的正确方法;其他方法风险代码注入漏洞。