【问题标题】:Calling an external program from python从 python 调用外部程序
【发布时间】:2009-06-23 00:51:14
【问题描述】:

所以我有这个 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 的优秀答案
  • 作为 shell 脚本,您可以通过将反引号中的命令输出保存到变量中进行优化,然后比较两个 if 语句中的变量 - 而不是运行两次代码。

标签: python c


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    这比加载 C 函数更简单。

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

    使用别人已经做过的东西还是比较简单的。

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 2012-03-08
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多