/ bin / sh:第62行:to:找不到命令

时间:2016-09-21 14:18:48

标签: python json shell hadoop subprocess

我有一个python代码,我在其中调用一个shell命令。我执行shell命令的代码部分是:

try:
    def parse(text_list):
        text = '\n'.join(text_list)
        cwd = os.getcwd()
        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(["echo '%s' | syntaxnet/demo.sh 2>/dev/null"%text], shell = True)
        os.chdir(cwd)
        return synnet_output
except Exception as e:
    sys.stdout.write(str(e))

现在,当我在带有一些示例输入的本地文件上运行此代码时(我做了cat /home/sree/example.json | python parse.py),它工作正常,我得到了所需的输出。但我试图在我的HDFS上输入代码(相同的cat命令,但输入文件路径来自HDFS),其中包含完全相同类型的json条目,并且失败并显示错误:

/bin/sh: line 62: to: command not found
list index out of range

我在Stack Overflow上阅读了类似的问题,解决方案是为正在调用的shell脚本添加一个Shebang行。我的#!/usr/bin/bash脚本中有shebang行demo.sh

此外,which bash提供了/usr/bin/bash

有人请详细说明。

2 个答案:

答案 0 :(得分:1)

您很少想要将列表参数与shell=True相结合。只需传递字符串:

synnet_output = subprocess.check_output("echo '%s' | syntaxnet/demo.sh 2>/dev/null"%(text,), shell=True)

但是,你真的不需要shell管道。

from subprocess import check_output
from StringIO import StringIO  # from io import StringIO in Python 3
synnet_output = check_output(["syntaxnet/demo.sh"],
                             stdin=StringIO(text),
                             stderr=os.devnull)

答案 1 :(得分:0)

我输入demo.sh的文字字符串中出现了一些特殊字符的问题。我通过将text存储到临时文件并将该文件的内容发送到demo.sh来解决了这个问题。

那是:

try:
    def parse(text_list):
        text = '\n'.join(text_list)
        cwd = os.getcwd()
        with open('/tmp/data', 'w') as f:
            f.write(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(["cat /tmp/data | syntaxnet/demo.sh 2>/dev/null"%text], shell = True)
        os.chdir(cwd)
        return synnet_output
except Exception as e:
    sys.stdout.write(str(e))