从python调用外部程序

时间:2009-06-23 00:51:14

标签: python c

所以我有这个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

2 个答案:

答案 0 :(得分:8)

就像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"

答案 1 :(得分:1)

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

这比加载C函数更简单。

如果你真的想从stupidfilter库中加载一个函数,那么首先要看看其他人是否已经完成了它。如果你找不到任何人,那么请阅读manual - 如何从Python调用C到那里。

使用其他人已经做过的事情仍然比较简单。

相关问题