我有一个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行。我有shebang行#!/usr/bin/bash
的demo.sh
脚本。
另外,which bash
给出/usr/bin/bash
。
请有人详细说明。
您很少(如果有的话)想要结合使用传递列表参数和shell=True
。只需传递字符串:
synnet_output = subprocess.check_output("echo '%s' | syntaxnet/demo.sh 2>/dev/null"%(text,), shell=True)
但是,您实际上并不需要外壳管道。
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句