kskp kskp - 2 months ago 20
Bash Question

Print variable in Shell command

I want to extract the text field from a json objcet of a tweet and run it through syntaxnet. I am doing it all in Python.

My code is:

import os, sys
import subprocess
import json

def parse(text):
os.chdir("/var/www/html/alenza/hdfs/user/alenza/sree_account/sree_project/src/core/data_analysis/syntaxnet/models/syntaxnet")
#synnet_output = subprocess.check_output()
subprocess.call(["echo 'hello world' | syntaxet/demo.sh"], shell = True)
#print synnet_output


for line in sys.stdin:
line1 = json.loads(line)
text = line1['avl_lexicon_text']
print text
synnet_output = parse(text)


Now, instead of
echo 'hello world'
in
parse
function, I want to echo
text
there. That is I want to feed the
text
variable to
syntaxnet/demo.sh
file. I tried doing
subprocess.call(["echo text | syntaxet/demo.sh"], shell = True)
but that did not work. How can I do that?

Answer

You can just use string formatter %s and substitute the text

def parse(text):
    os.chdir("/var/www/html/alenza/hdfs/user/alenza/sree_account/sree_project/src/core/data_analysis/syntaxnet/models/syntaxnet")
    #synnet_output = subprocess.check_output()
    subprocess.call(["echo '%s' | syntaxet/demo.sh"%text], shell = True)
    #print synnet_output

If you suspect that your text may have single quotes, then you can escape it:

text = text.replace("'", "\\'")
Comments