【问题标题】:AttributeError running python function from terminal and php exec从终端和php exec运行python函数的AttributeError
【发布时间】:2015-05-16 23:44:01
【问题描述】:

我想执行一个 python 类的函数。 Oauth.py

import....
class Oauth:
    def __init__(self, requesttokenurl, accesstokenurl, resourceurl, version):
        .....
    def getList(self):
        .......
        return list


if __name__ == "__main__":
    .......

我正在终端测试运行命令,我尝试运行以下命令。 命令:

python -c 'import Oauth; Oauth.getList()'

错误:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute 'getList'

命令:

python -c 'from Oauth import *; print getList()'

错误:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'getList' is not defined

命令:

python -c 'from Oauth import getList; print getList()'

错误:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: cannot import name getList

【问题讨论】:

    标签: php python terminal exec


    【解决方案1】:

    试试:

    python -c 'from Oauth import Oauth; Oauth(<args>).getList()'
    

    该模块名为Oauth,因此您尝试使用的类实际上是Oauth.Oauth。您需要创建一个实例来调用getList(),这就是为什么您需要添加括号(和一些参数)。以上等价于以下Python程序:

    import Oauth
    oa = Oauth.Oauth(<args>)
    oa.getList()
    

    不确定您需要哪些构造函数参数。

    【讨论】:

    • 我认为您可以将脚本的文件夹添加到您的PYTHONPATH,但make your script executable 并让脚本的if __name__ == '__main__' 部分为您执行getList() 打印可能更容易。或者你可以创建一个单独的脚本来做这个。
    • 我在命令中添加了 cd /var/www/folder/,我需要从 php 运行脚本并捕获响应。
    【解决方案2】:

    看了安德烈的回复后,我得到了这个错误:

    TypeError: __init__() takes exactly 5 arguments (2 given)
    

    构造函数需要5个参数,在这种情况下函数不需要参数。发送空参数。命令如下:

    python -c 'from Oauth import Oauth; print Oauth("", "", "", "").getList()'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多