繁体   English   中英

从python调用外部程序

[英]Calling an external program from 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

要像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库中加载一个函数,那么首先要看看其他人是否已经完成了它。 如果你找不到任何人,那么请阅读手册 - 如何从Python调用C到那里。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM