Print variable in Shell command
<p>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.</p>

<p>My code is:</p>

<pre><code>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)
</code></pre>

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

<p>You can just use string formatter <code>%s</code> and substitute the text </p>

<pre><code>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
</code></pre>

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

<pre><code>text = text.replace("'", "\\'")
</code></pre>

python shell arguments subprocess