为什么python脚本在pycharm中运行和在命令提示符中运行时行为不同?



当我从Linux命令提示符(bash)运行脚本时,我得到一个错误,但是当我直接在Pycharm中运行相同的脚本时,它工作得很好。

代码如下:

class EncodeKey:
def __new__(cls, *args):
if len(args) == 1:
return cls.generate_encode_key(args[0].upper())
return cls.get_encode_key(args)
...
...
if __name__ == '__main__':
encode_key = EncodeKey(*["something"])
print(encode_key)

正如我已经说过的,在Pycharm中,脚本工作正常,没有任何错误,但以下是我从命令提示符运行脚本时得到的结果:

user@machine:~/my/path/to/the/script$ python py.py
Traceback (most recent call last):
File "py.py", line 93, in <module>
encode_key = EncodeKey(*["something"])
TypeError: this constructor takes no arguments

或:

user@machine:~/my/path/to/the/script$ ls -lh
...
-rwxrwxr-x 1 user user  3.2K Jun 20 19:12 py.py
...
user@machine:~/my/path/to/the/script$ ./py.py
Traceback (most recent call last):
File "py.py", line 93, in <module>
encode_key = EncodeKey(*["something"])
TypeError: this constructor takes no arguments
当然,对于这样一个不寻常的问题,我没有找到任何解决方案。知道为什么会这样吗?如何解决呢?谢谢!

如果您以默认方式安装python,则python命令使用python 2。要使用Python 3进行解释,请使用命令python3:

user@machine:~/my/path/to/the/script$ python3 py.py

程序在Python 2中出错,因为旧式类(Python 2中的默认类)不支持__new__。如果你需要支持Python 2,通过扩展object:

使你的类成为new-style。
class EncodeKey(object):

如果你这样做,你的代码仍然可以在Python 3中工作。

最新更新