问题
I am trying to run a shell script from python by exporting the python variable to the shell script instead of directly reading them from the user. A question regarding passing array values as variable to shell script was answered successfully earlier and helped me to pass the values in an array as a input variable to the shell script. I want to export multiple variables such as FLUID
, TTYPE
and FLIBRARY
from the following python script:
FLUID="MDM"
TTYPE=0
FLIBRARY="RefProp"
HSPACE=[0.01, 0.009, 0.008, 0.007]
subprocess.call(['./testfile1'] + [str(n) for n in HSPACE])
to the following shell script named testfile1:
#!/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
回答1:
You could set them as environment variables within the Python script:
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])
回答2:
Is it an option for you to pass the variables as parameters?
subprocess.call(['./testfile1 %s %s' % (FLUID, FLIBRARY)] + [str(n) for n in HSPACE])
and in the bash script
#!/bin/bash
FLUID=$1
FLIBRARY=$2
echo "$FLUID, $FLIBRARY" | ./vls.exe
回答3:
Through the environment
#!/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})
...thereafter, in shell:
#!/bin/bash
hspace=( "$@" )
declare -p fluid ttype flibrary hspace # print values
...output being:
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")'
On the command line
Another approach is to use positional arguments.
#!/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])
...and, in shell:
#!/bin/bash
fluid=$1; shift
ttype=$2; shift
flibrary=$3; shift
hspace=( "$@" )
declare -p fluid ttype flibrary hspace # print values
...output being:
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")'
Note:
- Use of
awk -v var="$val"
is the correct way to pass variable values from bash to awk; other approaches risk code injection vulnerabilities. - Use of lower-case names for user-defined environment variables is compliant with POSIX convention to avoid namespace collisions; see relevant spec.
来源:https://stackoverflow.com/questions/37449327/passing-multiple-variables-from-python-script-to-shell-script