【问题标题】:Print variable in Shell commandShell命令中的打印变量
【发布时间】:2017-01-28 19:43:59
【问题描述】:

我想从推文的 json 对象中提取文本字段并通过 syntaxnet 运行它。我都是用 Python 做的。

我的代码是:

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)

现在,我想在parse 函数中回显text,而不是echo 'hello world'。那就是我想将text 变量提供给syntaxnet/demo.sh 文件。我尝试做subprocess.call(["echo text | syntaxet/demo.sh"], shell = True),但没有奏效。我该怎么做?

【问题讨论】:

    标签: python shell arguments subprocess


    【解决方案1】:

    您可以只使用字符串格式化程序%s 并替换文本

    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
    

    如果你怀疑你的文本可能有单引号,那么你可以转义它:

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

    【讨论】:

    • 像魅力一样工作。谢谢!
    最近更新 更多