从Python调用外部程序

3

我有一个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


我更改了标题,这样搜索此问题的人就可以找到noskio的优秀答案。 - Martin Beckett
作为一个shell脚本,你可以通过将命令的输出保存在反引号中的变量中来进行优化,然后在两个if语句中比较该变量,而不是运行两次代码。 - Jonathan Leffler
2个回答

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

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

这比加载C函数简单。

如果你真的想从stupidfilter库加载一个函数,那么首先看看是否有其他人已经做过了。如果找不到任何人已经这样做,那么请阅读 手册 - 如何从Python调用C在其中讨论。

使用别人已经做过的仍然更简单。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接