【问题标题】:/bin/sh: line 62: to: command not found/bin/sh: line 62: to: command not found
【发布时间】:2017-01-29 20:40:35
【问题描述】:

我有一个 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 行。我在demo.sh 脚​​本中有shebang 行#!/usr/bin/bash

另外,which bash 提供/usr/bin/bash

请有人详细说明。

【问题讨论】:

标签: python json shell hadoop subprocess


【解决方案1】:

在我输入到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))

【讨论】:

    【解决方案2】:

    如果有的话,您很少希望将传递列表参数与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,我仍然遇到同样的错误。它在我的主目录中运行良好,但在 HDFS 上输入失败。对于第二个,我得到一个错误:StringIO instance has no attribute 'fileno'
    • 这里有几个问题。首先,您确定demo.sh 可以从标准输入中读取吗?其次,HDFS 不是一个常规的文件系统,需要使用特殊的工具来与它的内容进行交互。
    • 我确信demo.sh 可以从标准输入中读取。因为完全相同的代码适用于我的主目录中的输入文件,该文件包含 HDFS 上文件的前 4 个条目。我假设 HDFS 上的文件中有一些数据令人困惑demo.sh。将很快更新。感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 2020-01-28
    • 2022-12-21
    • 2020-09-26
    • 2015-09-04
    • 1970-01-01
    • 2013-02-17
    • 2015-09-29
    • 1970-01-01
    相关资源
    最近更新 更多