NameError: name 'ResourceWarning' is not defined - python

java version "1.8.0_311"
Python 3.10.8
Sikuli:-
<dependency>
<groupId>sikulixapi</groupId>
<artifactId>sikulixapi</artifactId>
<scope>system</scope>
<version>2.0.5</version>
<systemPath>${project.basedir}/sikulixapi-2.0.5.jar</systemPath>
</dependency>
I am getting the below error while running a sample python program from java.
Exception in thread "main" Traceback (most recent call last):
File "foo\boo\sikulixapi-2.0.5.jar\Lib\site.py", line 68, in <module>
File "foo\boo\sikulixapi-2.0.5.jar\Lib\os.py", line 64, in <module>
File "foo\boo\sikulixapi-2.0.5.jar\Lib\ntpath.py", line 12, in <module>
File "foo\boo\sikulixapi-2.0.5.jar\Lib\warnings.py", line 395, in <module>
File "foo\boo\sikulixapi-2.0.5.jar\Lib\warnings.py", line 395, in <module>
File "__pyclasspath__/_warnings.py", line 105, in <module>
NameError: name 'ResourceWarning' is not defined
Python:-
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print('Hello world!')
Java
package Types.UserInterface.Utilities;
import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;
public class InterpreterExample {
PythonInterpreter interpreter = null;
public InterpreterExample() {
PythonInterpreter.initialize(System.getProperties(),
System.getProperties(), new String[0]);
this.interpreter = new PythonInterpreter();
}
void execfile(final String fileName) {
this.interpreter.execfile(fileName);
}
PyInstance createClass(final String className, final String opts) {
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
public static void main(String gargs[]) {
InterpreterExample ie = new InterpreterExample();
ie.execfile("hello.py");
PyInstance hello = ie.createClass("Hello", "None");
hello.invoke("run");
}
}
Not sure why it is conflicting with sikuli classes while running the sample java program.
Note: Python program works perfectly fine when they are executed directly. Problem raises only when the same program is called in java.
Could someone give a direction as to what is the approach to fix this?

cf Learning how to use Jython - ResourceWarning error
Jython currently only works with Python 2, you can't use Python 3 with it (for now), hence the error.

Related

NameError: name 'sys' is not defined appears with buildozer

I tried to made an Android app with the Package tapo-plug, kivy and buildozer, but the app crashes directly after opening it. I never did something like this before. This is the Error-message send by my phone:
02-04 16:32:53.560 23072 23113 I python : Traceback (most recent call last):
02-04 16:32:53.561 23072 23113 I python : File "/home/daniel/test/ServerManagementApp/.buildozer/android/app/main.py", line 19, in <module>
02-04 16:32:53.561 23072 23113 I python : File "/home/daniel/test/ServerManagementApp/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/Vexludus/arm64-v8a/tapo_plug/tapoPlugApi.py", line 11, in <module>
02-04 16:32:53.561 23072 23113 I python : File "/home/daniel/test/ServerManagementApp/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/Vexludus/arm64-v8a/tapo_plug/tapoEncryption.py", line 7, in <module>
02-04 16:32:53.561 23072 23113 I python : File "/home/daniel/test/ServerManagementApp/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/Vexludus/arm64-v8a/Crypto/PublicKey/RSA.py", line 38, in <module>
02-04 16:32:53.561 23072 23113 I python : File "/home/daniel/test/ServerManagementApp/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/Vexludus/arm64-v8a/Crypto/IO/PKCS8.py", line 44, in <module>
02-04 16:32:53.561 23072 23113 I python : File "/home/daniel/test/ServerManagementApp/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/Vexludus/arm64-v8a/Crypto/IO/_PBES.py", line 43, in <module>
02-04 16:32:53.561 23072 23113 I python : File "/home/daniel/test/ServerManagementApp/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/Vexludus/arm64-v8a/Crypto/Hash/MD5.py", line 45, in <module>
02-04 16:32:53.561 23072 23113 I python : NameError: name 'sys' is not defined
02-04 16:32:53.561 23072 23113 I python : Python for android ended.
I already set tapo-plug,Crypto,PyCryptodome,pyjwkest,pycrypto as requirements.
This is my first time doing something like this.
This is the script-part the error occurs in:
from Crypto.Util.py3compat import *
from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
VoidPointer, SmartPointer,
create_string_buffer,
get_raw_buffer, c_size_t,
c_uint8_ptr)
_raw_md5_lib = load_pycryptodome_raw_lib("Crypto.Hash._MD5",
"""
#define MD5_DIGEST_SIZE 16
int MD5_init(void **shaState);
int MD5_destroy(void *shaState);
int MD5_update(void *hs,
const uint8_t *buf,
size_t len);
int MD5_digest(const void *shaState,
uint8_t digest[MD5_DIGEST_SIZE]);
int MD5_copy(const void *src, void *dst);
int MD5_pbkdf2_hmac_assist(const void *inner,
const void *outer,
const uint8_t first_digest[MD5_DIGEST_SIZE],
uint8_t final_digest[MD5_DIGEST_SIZE],
size_t iterations);
""")
It's hard to guess what cause your issue without minimal reproductable sample. I made simple Kivy project, it works without issues under Windows and Android.
buildozer.spec requirements:
requirements = python3,kivy,pycryptodome,pkcs7,Crypto,tapo-plug,requests,urllib3,charset_normalizer,chardet,idna
Sample code:
from kivy.app import App
from Crypto.Util.py3compat import * # pip install pycryptodome
from Crypto.Hash.MD5 import *
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from tapo_plug import tapoPlugApi # pip install tapo-plug
class app(App):
device = {
"tapoIp": "127.0.0.1",
"tapoEmail": "dummy#dummy.com",
"tapoPassword": "dummy"
}
def build(self):
return BoxLayout(orientation='vertical')
def on_start(self):
self.root.add_widget(Label(text=str(b('test'))))
self.root.add_widget(Label(text=MD5Hash(b'test').hexdigest()))
try:
self.root.add_widget(Label(text=tapoPlugApi.getDeviceInfo(self.device)))
except Exception as e:
self.root.add_widget(Label(text=str(e)))
pass
app().run()

MAP++ on Windows with Python

I am trying to run MAP++ on Windows using the python driver. I downloaded the package from https://bitbucket.org/mmasciola/map-plus-plus/src/master/. When running it, I’m getting the following error:
AttributeError: function 'map_offset_fairlead' not found
I’ve tried Python 3 and 2, both give errors. In mapsys.py I’m using
lib = cdll.LoadLibrary("map_x64.dll")
and I have the map_x64.dll stored directly in the folder containing the mapsys.py script. Maybe I have an old version of the dll? Where do I get most recent one?
Full log:
File "main.py", line 35, in <module>
from mapsys import *
File "H:\mooring_linearisation\map\map-plus-plus\mmasciola-map-plus-plus-79719397feaa\python_driver\mapsys.py", line 28, in <module>
class Map(object):
File "H:\mooring_linearisation\map\map-plus-plus\mmasciola-map-plus-plus-79719397feaa\python_driver\mapsys.py", line 626, in Map
lib.map_offset_fairlead.argtypes = [MapInput_Type, c_int, c_double, c_double, c_double, c_char_p, POINTER(c_int)]
File "C:\Users\gkb20193\Miniconda3\envs\map_py2\lib\ctypes\__init__.py", line 379, in __getattr__
func = self.__getitem__(name)
File "C:\Users\gkb20193\Miniconda3\envs\map_py2\lib\ctypes\__init__.py", line 384, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'map_offset_fairlead' not found

error trying to use marshmallow_dataclass

I am trying to use marshmallow_dataclass in a python (3.9) test in pycharm to try it (marshmallow_dataclass) out and get an error.
Not sure what I am doing wrong. I have installed marshmallow_dataclass (8.1.0)
I have so far been successful in using marshmallow (3.8.0) and marshmallow_oneofschema (2.1.0) so far
(new to python but not programming)
Code is:
import marshmallow_dataclass
import unittest
class Tests(unittest.TestCase):
def test_serialize(self):
print("Hello")
Error is:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pycharm\_jb_unittest_runner.py", line 35, in <module>
sys.exit(main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING))
File "C:\xxxx\AppData\Local\Programs\Python\Python39\lib\unittest\main.py", line 100, in __init__
self.parseArgs(argv)
File "C:\xxxx\AppData\Local\Programs\Python\Python39\lib\unittest\main.py", line 147, in parseArgs
self.createTests()
File "C:\xxxx\AppData\Local\Programs\Python\Python39\lib\unittest\main.py", line 158, in createTests
self.test = self.testLoader.loadTestsFromNames(self.testNames,
File "C:\xxxx\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 220, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "C:\xxxx\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 220, in <listcomp>
suites = [self.loadTestsFromName(name, module) for name in names]
File "C:\xxxx\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
File "C:\xxxx\dev\repos\python\solar\pvoutput-publisher\test\test_serialization\test_delme.py", line 1, in <module>
import marshmallow_dataclass
File "C:\xxxx\AppData\Local\Programs\Python\Python39\lib\site-packages\marshmallow_dataclass\__init__.py", line 59, in <module>
import typing_inspect
File "C:\xxxx\AppData\Local\Programs\Python\Python39\lib\site-packages\typing_inspect.py", line 25, in <module>
from typing_extensions import Literal
File "C:\xxxx\AppData\Local\Programs\Python\Python39\lib\site-packages\typing_extensions.py", line 2084, in <module>
def TypeAlias(self, parameters):
TypeError: __init__() missing 1 required positional argument: 'doc'```
I hit similar error on python 3.9 alpha release (3.9.0a5), I am not sure the version of typing_extensions.py in your environment (maybe it is v3.7.4.3 ?).
The root cause is that :
the function TypeAlias() is decorated directly with the class _TypeAliasForm, which is subclass of typing._SpecialForm in python stardard library
typing._SpecialForm.__init__() in your python environment has extra argument doc , since the class _TypeAliasForm is a decorator for TypeAlias(), Python couldn't provide extra argument doc when instantiating _TypeAliasForm on decorating process.
In short, your typing_extensions.py is out of sync with your python interpreter, see the source code for detail:
TypeAlias() and _TypeAliasForm class .
typing._SpecialForm.__init__() in python 3.9.0a5
typing._SpecialForm.__init__() in python 3.9.0a6
It seems that the issue happens from python 3.9.0a1 to 3.9.0a5, so the solutions are :
upgrade your python to final release version
if you are not allowed to upgrade python for some other reasons, maybe you can monkey-patch typing._SpecialForm , here is the example for monkey-patching :
from typing import _SpecialForm
origin_getitem = _SpecialForm.__getitem__
def patch_init(self, name, doc=None):
if doc is None and callable(name):
if hasattr(name, '__doc__'):
doc = name.__doc__
self._name = name
self._doc = doc
def patch_getitem(self, parameters):
item = None
if callable(self._name):
item = self._name(self=self, parameters=parameters)
else:
item = origin_getitem(self=self, parameters=parameters)
return item
if not hasattr(_SpecialForm.__init__, 'patched'):
_SpecialForm.__init__ = patch_init
setattr(_SpecialForm.__init__, 'patched', True)
if not hasattr(_SpecialForm.__getitem__, 'patched'):
_SpecialForm.__getitem__ = patch_getitem
setattr(_SpecialForm.__getitem__, 'patched', True)

Script works on PyCharm but not in terminal

I am working on some API script in Python, it takes one argument and returns JSON. I am using BrawlStats library (https://github.com/SharpBit/brawlstats). It works very well in PyCharm but doesn't work in terminal, I have no idea why, I tried few suggestions like running "pip install" in script directory but it still doesn't help. I ma trying to run the script using PHP but it returns the same error as terminal: https://gyazo.com/afac3d7c7e50b4c4925ec767dc5457b2 + https://gyazo.com/5a55668e5e4cd005a64dd5c702043b98. Help would be really appreciated, I am stuck and I don't know how to fix it :/
Code:
import brawlstats
import json
import sys
client = brawlstats.Client("***")
def OMEGA(LUL):
player = client.get_profile(LUL)
xxDD = {
"tag": player.tag,
"name": player.name,
"avatar": player.avatar_url,
"trophies": player.trophies,
"victories": player.victories,
"level": player.exp_level
}
print(json.dumps(xxDD))
return json.dumps(xxDD)
print(sys.argv[1])
OMEGA(sys.argv[1])
and here is error when I run it using PHP/terminal:
Traceback (most recent call last):
File "C:/xampp/htdocs/main.py", line 23, in <module>
OMEGA(sys.argv[1])
File "C:/xampp/htdocs/main.py", line 8, in OMEGA
player = client.get_profile(LUL)
File "C:\Users\Krzysztof\AppData\Local\Programs\Python\Python36\lib\site-packages\brawlstats\core.py", line 147, in get_profile
data, resp = self._get(self.api.profile + '/' + tag)
File "C:\Users\Krzysztof\AppData\Local\Programs\Python\Python36\lib\site-packages\brawlstats\core.py", line 124, in _get
with self.session.get(url, timeout=self.timeout, headers=self.headers) as resp:
AttributeError: __enter__
Last thing, here is output when I run it using PyCharm:
{"tag": "CP0GU982", "name": "flick", "avatar": "https://fourjr.github.io/bs-assets/player_icons/28000000.png", "trophies": 6, "victories": 1, "level": 1}

Invalid syntax while running test on Travis

I'm having a problem with Travis on every commit. My tests work on local but on Travis I get this error:
Traceback (most recent call last):
File "/opt/python/3.2.5/lib/python3.2/unittest/case.py", line 370, in _executeTestPart
function()
File "/opt/python/3.2.5/lib/python3.2/unittest/loader.py", line 32, in testFailure
raise exception
ImportError: Failed to import test module: test.test_parser
Traceback (most recent call last):
File "/opt/python/3.2.5/lib/python3.2/unittest/loader.py", line 261, in _find_tests
module = self._get_module_from_name(name)
File "/opt/python/3.2.5/lib/python3.2/unittest/loader.py", line 239, in _get_module_from_name
__import__(name)
File "/home/travis/build/davidmogar/genderator/test/test_parser.py", line 5, in <module>
import genderator
File "/home/travis/build/davidmogar/genderator/genderator/__init__.py", line 3, in <module>
from genderator.parser import Parser
File "/home/travis/build/davidmogar/genderator/genderator/parser.py", line 5, in <module>
from .utils import Normalizer
File "/home/travis/build/davidmogar/genderator/genderator/utils.py", line 63
u'\N{COMBINING TILDE}'
^
SyntaxError: invalid syntax
Here is the code where that line is:
def remove_accent_marks(text):
good_accents = {
u'\N{COMBINING TILDE}',
u'\N{COMBINING CEDILLA}'
}
return ''.join(c for c in unicodedata.normalize('NFKD', text)
if unicodedata.category(c) != 'Mn' or c in good_accents)
I have no idea about what is the problem because as I've said, all test are working in local. Here is my .travis.yml file:
language: python
python:
- "3.2"
- "3.3"
- "3.4"
script: python -m unittest discover
Any idea?
The u'...' syntax in Python 3 is only supported in Python 3.3 and up.
The u prefix is only there to support polyglot Python code (supporting both 2 and 3), and can be safely removed if you don't need to support Python 2.
If you need to support both Python 2 and 3.2, you'll have to use a different approach. You could use a from __future__ import to make all string literals in Python 2 produce unicode string objects; this applies per module:
from __future__ import unicode_literals
def remove_accent_marks(text):
good_accents = {
'\N{COMBINING TILDE}',
'\N{COMBINING CEDILLA}'
}
The strings will be treated as Unicode in both Python 2 and 3.
Or you could create your own polyglot function:
import sys
if sys.version_info[0] < 3:
u = lambda s: unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
else:
u = lambda s: s
and use that on all your Unicode strings:
def remove_accent_marks(text):
good_accents = {
u('\N{COMBINING TILDE}'),
u('\N{COMBINING CEDILLA}')
}
or you can use the six library to produce that bridge for you:
import six
def remove_accent_marks(text):
good_accents = {
six.u('\N{COMBINING TILDE}'),
six.u('\N{COMBINING CEDILLA}')
}
You may want to read the Python Porting HOWTO.

Categories

Resources