Home > Mobile >  Why does a python script behaves differently when it is run in pycharm and when it is run from a com
Why does a python script behaves differently when it is run in pycharm and when it is run from a com

Time:06-21

I'm getting an error when I run a script from the Linux command prompt(bash), but when I run the same script in the Pycharm directly, it works fine.

Here is the code:

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)

As I already told, in the Pycharm the script works fine without any errors, but here is what I'm getting when the script is run from the command prompt:

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

Or:

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

Of, course, I didn't find any solutions on such an unusual problem. Any ideas why is that happening ? And how to solve it ? Thanks !

CodePudding user response:

If you've installed python in the default way, the python command uses Python 2. To interperet with Python 3, use the command python3:

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

The program errors in Python 2 because old-style classes, the default in Python 2, do not support __new__. If you need to support Python 2, make your class new-style by extending object:

class EncodeKey(object):

Your code will still work in Python 3 if you do this.

CodePudding user response:

Maybe you need to enter your virtual environment in the terminal. Open the terminal in you folder.

Type:

.\venv\Scripts\activate

Then run your app from inside the virtual env.

If I'm correct, global Python can't find your local dependencies inside your venv.

  • Related