从python调用外部程序

2024-04-25 06:45:48 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个shell脚本:

echo "Enter text to be classified, hit return to run classification."
read text

if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "1.000000" ]
 then
  echo "Text is not likely to be stupid."
fi

if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "0.000000" ]
 then
  echo "Text is likely to be stupid."
fi

我想用python编写它。我该怎么做?在

(如您所见,它使用库http://stupidfilter.org/stupidfilter-0.2-1.tar.gz


Tags: totextechodataifbinisbe
2条回答

要像shell脚本那样执行此操作,请执行以下操作:

import subprocess

text = raw_input("Enter text to be classified: ")
p1 = subprocess.Popen('bin/stupidfilter', 'data/c_trbf')
stupid = float(p1.communicate(text)[0])

if stupid:
    print "Text is likely to be stupid"
else:
    print "Text is not likely to be stupid"

您可以清楚地将命令作为子shell运行并读取返回值,就像在shell脚本中一样,然后在Python中处理结果。在

这比加载C函数更简单。在

如果您真的想从stupidfilter库加载函数,那么首先查看是否有其他人已经完成了该操作。如果您找不到任何人,那么请阅读manual-如何从Python调用到C中。在

使用别人已经做过的事情还是比较简单的。在

相关问题 更多 >