wondering if anyone can help me figure out why I am not catching the TimeExhausted exception when using
wait_for_transaction_receipt()
from web3.py
I want the error to be thrown after waiting 45 seconds, I want to catch the error, then go do some other stuff, and wait again. I want to repeat this cycle until the transaction is mined & then exit / break. I think it's a simple syntax issue but not sure -- last time the exception was raised, my code didn't catch it, and instead it lead to an AttributeError
here's my code:
from web3 import Web3
while True:
try:
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=45)
print(f"{str(dt.utcnow())[:-7]} | Transaction receipt: {tx_receipt}")
break
except Web3.TimeExhausted as e:
print(f"{str(dt.utcnow())[:-7]} | A Inner exception caught: {e}.")
print(
f"{str(dt.utcnow())[:-7]} | Timed out waiting for transaction. "
+ f"Will update SMA & wait again..."
)
update_sma_data()
pass
Finally here is my error text:
Traceback (most recent call last):
File "/home/flim/.local/lib/python3.8/site-packages/web3/eth.py", line 783, in wait_for_transaction_receipt
_timeout.sleep(poll_latency)
File "/home/flim/.local/lib/python3.8/site-packages/web3/_utils/threads.py", line 89, in sleep
self.check()
File "/home/flim/.local/lib/python3.8/site-packages/web3/_utils/threads.py", line 82, in check
raise self
web3._utils.threads.Timeout: 45 seconds
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "money-maker-mike.py", line 301, in sign_and_send_tx
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=45)
File "/home/flim/.local/lib/python3.8/site-packages/web3/eth.py", line 787, in wait_for_transaction_receipt
raise TimeExhausted(
web3.exceptions.TimeExhausted: Transaction HexBytes('0xd60bc63a96b5b81b98ca39308fc9ab709d2f2ccfd1b03c064db285f954633d34') is not in the chain after 45 seconds
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "money-maker-mike.py", line 529, in <module>
main()
File "money-maker-mike.py", line 522, in main
trade()
File "money-maker-mike.py", line 373, in trade
zero_ex_trade(sell_token, buy_token, sell_amount)
File "money-maker-mike.py", line 278, in zero_ex_trade
sign_and_send_tx(tx)
File "money-maker-mike.py", line 306, in sign_and_send_tx
except Web3.TimeExhausted as e:
AttributeError: type object 'Web3' has no attribute 'TimeExhausted'
Thanks in advance :D
from web3.exceptions import TimeExhausted
try:
...
except TimeExhausted as e:
...
Source: web3.py/test_transactions.py at master · eric-s321/web3.py
Related
This is my current code:
import psutil
count = 0
while count < 3000000000:
for process in psutil.process_iter():
if process.name().lower() == 'chrome.exe':
print(process)
process.terminate()
count = count + 1
else:
print('no')
print(count)
its scanning all of he processes running. It then crashes when it scans:
' WindowsInternal.ComposableShell.Experiences.TextInput.Inpu...'
This is the windows service for the on screen keyboard. I tried to stop it running however it still runs. I was wondering if i could give my python file full permissions so this stops happening.
This is the error code from the terminal:
Traceback (most recent call last):
File "C:\Users\benmi\PycharmProjects\HelloWorld\venv\lib\site-packages\psutil_common.py", line 449, in wrapper
ret = self._cache[fun]
AttributeError: _cache
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\benmi\PycharmProjects\HelloWorld\venv\lib\site-packages\psutil_pswindows.py", line 679, in wrapper
return fun(self, *args, **kwargs)
File "C:\Users\benmi\PycharmProjects\HelloWorld\venv\lib\site-packages\psutil_common.py", line 452, in wrapper
return fun(self)
File "C:\Users\benmi\PycharmProjects\HelloWorld\venv\lib\site-packages\psutil_pswindows.py", line 766, in exe
exe = cext.proc_exe(self.pid)
PermissionError: [WinError 24] The program issued a command but the command length is incorrect: '(originated from NtQuerySystemInformation)'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/benmi/PycharmProjects/HelloWorld/TerminateProgram.py", line 5, in
if process.name().lower() == 'chrome.exe':
File "C:\Users\benmi\PycharmProjects\HelloWorld\venv\lib\site-packages\psutil__init__.py", line 630, in name
name = self._proc.name()
File "C:\Users\benmi\PycharmProjects\HelloWorld\venv\lib\site-packages\psutil_pswindows.py", line 750, in name
return os.path.basename(self.exe())
File "C:\Users\benmi\PycharmProjects\HelloWorld\venv\lib\site-packages\psutil_pswindows.py", line 681, in wrapper
raise convert_oserror(err, pid=self.pid, name=self._name)
psutil.AccessDenied: psutil.AccessDenied (pid=8612)
I'm trying to get this, https://github.com/joaquinlpereyra/twitterImgBot, to work
and it works and it seems ok.
But after some hours, it stops working and this error comes up:
*python3 twitterbot.py
Traceback (most recent call last):
File "/home/user/.local/lib/python3.7/site-packages/tweepy/binder.py", line 118, in build_path
value = quote(self.session.params[name])
KeyError: 'id'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "twitterbot.py", line 209, in <module>
main()
File "twitterbot.py", line 200, in main
orders()
File "twitterbot.py", line 118, in orders
timeline.delete_tweet_by_id(tweet.in_reply_to_status_id, api)
File "/home/user/Skrivebord/twitterboot/lo/bot/timeline.py", line 12, in delete_tweet_by_id
api.destroy_status(id_to_delete)
File "/home/user/.local/lib/python3.7/site-packages/tweepy/binder.py", line 245, in _call
method = APIMethod(args, kwargs)
File "/home/user/.local/lib/python3.7/site-packages/tweepy/binder.py", line 71, in __init__
self.build_path()
File "/home/user/.local/lib/python3.7/site-packages/tweepy/binder.py", line 120, in build_path
raise TweepError('No parameter value found for path variable: %s' % name)
tweepy.error.TweepError: No parameter value found for path variable: id*
It seems like the Python has some problem because if I make a new install on a another PC it works for some hours and then stops.
Strange.
This is likely because tweet is not in reply to a status, so has an in_reply_to_status_id attribute that's None, so API.destroy_status is called with an id of None.
I have this exception defined:
class ArgumentsException(Exception):
"""Exception that is raised when incorrect arguments are used."""
pass
Now I run my test where I run my program through sh package. And when it raises this expected exception, sh catches that exception itself and then reraises his own exception. Is there a way for me to check if my original exception was raised somehow?
For example when I run this code (this code is expected to raise that exception):
sh.python3(
self.main_py_path,
self.live_cfg_path,
self.workflow_cfg_path)
I get this exception instead:
Traceback (most recent call last):
File "/home/oerp/src/devops-tools/tests/test_main.py", line 153, in test_full_workflow_1
self.workflow_cfg_path)
File "/usr/local/lib/python3.5/dist-packages/sh.py", line 1427, in __call__
return RunningCommand(cmd, call_args, stdin, stdout, stderr)
File "/usr/local/lib/python3.5/dist-packages/sh.py", line 774, in __init__
self.wait()
File "/usr/local/lib/python3.5/dist-packages/sh.py", line 792, in wait
self.handle_command_exit_code(exit_code)
File "/usr/local/lib/python3.5/dist-packages/sh.py", line 815, in handle_command_exit_code
raise exc
sh.ErrorReturnCode_1:
RAN: /usr/bin/python3 /home/oerp/src/devops-tools/main.py /home/oerp/src/devops-tools/tests/configs/__live__.py /home/oerp/src/devops-tools/tests/configs/__workflow__.py
STDOUT:
STDERR:
Traceback (most recent call last):
File "/home/oerp/src/devops-tools/main.py", line 204, in <module>
state = _get_state(args.state, ignore_state=args.ignore_state)
File "/home/oerp/src/devops-tools/main.py", line 68, in _get_state
"__state__.py file must be provided if --ignore-state flag "
exceptions.ArgumentsException: __state__.py file must be provided if --ignore-state flag is not used.
Well I can do something like:
self.assertTrue('ArgumentsException' in str(e.stderr))
But maybe there is more elegant way to check my exception?
I am trying to log the pyodbc exception to a log file, the problem is, using the standard python logging, the code produces another exception related to encoding some unidentified characters (looks like Chines) that appears in the exception args, the exception stack trace:
Exception: [23000] [Oracle][ODBC][Ora]ORA-00001: unique constraint
(REDWOOD.TITLE_PK) violated ORA-06512: at line 53 ઊȯ 诔唱 㸸ੌȯ s ઉȯ
㸸ੌȯ ꦓ倗翸 ᴘඇȯ 㫏杦翸 ɘઊȯ 텈ઉȯ 㸸ੌȯ 糆倘翸 ! H
촼杧翸 (1) (SQLExecDirectW)
--- Logging error --- Traceback (most recent call last): File "\Transfer\transfer\transfer_records.py", line 123, in transfer_record
row.PUBSTAT, row.CITED) File "\Transfer\transfer\db_access.py", line 476, in transfer_record
self.cursor.execute(sql_block, params)
pyodbc.IntegrityError: ('23000', '[23000]
[Oracle][ODBC][Ora]ORA-00001: unique constraint (REDWOOD.TITLE_PK)
violated\nORA-06512: at line
53\n\x00ઊȯ\x00诔唱\x00\x00㸸ੌȯ\x00\x00\x00s\x00\uec40ઉȯ\x00\x00\uf600\x00\x00㸸ੌȯ\x00ꦓ倗翸\x00ᴘඇȯ\x00㫏杦翸\x00ɘઊȯ\x00텈ઉȯ\x00㸸ੌȯ\x00糆倘翸\x00\x00\x00\x01\x00!\x00\x00\x00H\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00촼杧翸\x00
(1) (SQLExecDirectW)')
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"C:\Python\lib\logging__init__.py", line 994, in emit
stream.write(msg) File "C:\Python\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in
position 167-168: character maps to Call stack: File
"/Transfer/trans_ui.py", line 162, in
app.mainloop() File "C:\Python\lib\tkinter__init__.py", line 1277, in mainloop
self.tk.mainloop(n) File "C:\Python\lib\tkinter__init__.py", line 1699, in call
return self.func(*args) File "/Transfer/trans_ui.py", line 130, in transfer_records
start_transfer.main(options=options, app=self) File "\Transfer\start_transfer.py", line 19, in main
transfer.start() File "Transfer\transfer\transfer_records.py", line 46, in start
list(map(self.transfer_record, self.transfer_rows)) File "Transfer\transfer\transfer_records.py", line 145, in transfer_record
logging.error("Exception details: " + ex.args[1]) Message: 'Exception details: [23000] [Oracle][ODBC][Ora]ORA-00001: unique
constraint (THOTH.TITLE_PK) violated\nORA-06512: at line
53\n\x00ઊȯ\x00诔唱\x00\x00㸸ੌȯ\x00\x00\x00s\x00\uec40ઉȯ\x00\x00\uf600\x00\x00㸸ੌȯ\x00ꦓ倗翸\x00ᴘඇȯ\x00㫏杦翸\x00ɘઊȯ\x00텈ઉȯ\x00㸸ੌȯ\x00糆倘翸\x00\x00\x00\x01\x00!\x00\x00\x00H\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00촼杧翸\x00
(1) (SQLExecDirectW)' Arguments: () Total Time: 24.116901397705078
Process finished with exit code 0
The Exception handler that produces the exception:
except pyodbc.Error as ex:
print("Exception: ", ex.args[1])
self.database.rollback()
self.records_counter['transfer_errors'] += 1
logging.error("Exception details: " + ex.args[1])
self.status_update("An Exception Occurred while transferring
record: " + row.CTRLNO + "-" + row.LEVL + " Details:" +
ex.args[1], msgbox='Error')
What are these characters that appears as part of the exception args?
How I can get rid of them as it seems they are producing the encoding exception
You can get rid of them by encoding explicitly so that you can use errors="replace" or ignore The resulting bytes will not be pretty but they will be logged.
logging.error("Exception: " + str(ex.args[1].encode(encoding='charmap', errors='replace')))
I'm using the Pool function of the multiprocessing module in order to run the same code in parallel on different data.
It turns out that on some data my code raises an exception, but the precise line in which this happens is not given:
Traceback (most recent call last):
File "my_wrapper_script.py", line 366, in <module>
main()
File "my_wrapper_script.py", line 343, in main
results = pool.map(process_function, folders)
File "/usr/lib64/python2.6/multiprocessing/pool.py", line 148, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib64/python2.6/multiprocessing/pool.py", line 422, in get
raise self._value
KeyError: 'some_key'
I am aware of multiprocessing.log_to_stderr() , but it seems that it is useful when concurrency issues arise, which is not my case.
Any ideas?
If you're using a new enough version of Python, you'll actually see the real exception get printed prior to that one. For example, here's a sample that fails:
import multiprocessing
def inner():
raise Exception("FAIL")
def f():
print("HI")
inner()
p = multiprocessing.Pool()
p.apply(f)
p.close()
p.join()
Here's the exception when running this with python 3.4:
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/usr/local/lib/python3.4/multiprocessing/pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "test.py", line 9, in f
inner()
File "test.py", line 4, in inner
raise Exception("FAIL")
Exception: FAIL
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test.py", line 13, in <module>
p.apply(f)
File "/usr/local/lib/python3.4/multiprocessing/pool.py", line 253, in apply
return self.apply_async(func, args, kwds).get()
File "/usr/local/lib/python3.4/multiprocessing/pool.py", line 599, in get
raise self._value
Exception: FAIL
If using a newer version isn't an option, the easiest thing to do is to wrap your worker function in a try/except block that will print the exception prior to re-raising it:
import multiprocessing
import traceback
def inner():
raise Exception("FAIL")
def f():
try:
print("HI")
inner()
except Exception:
print("Exception in worker:")
traceback.print_exc()
raise
p = multiprocessing.Pool()
p.apply(f)
p.close()
p.join()
Output:
HI
Exception in worker:
Traceback (most recent call last):
File "test.py", line 11, in f
inner()
File "test.py", line 5, in inner
raise Exception("FAIL")
Exception: FAIL
Traceback (most recent call last):
File "test.py", line 18, in <module>
p.apply(f)
File "/usr/local/lib/python2.7/multiprocessing/pool.py", line 244, in apply
return self.apply_async(func, args, kwds).get()
File "/usr/local/lib/python2.7/multiprocessing/pool.py", line 558, in get
raise self._value
Exception: FAIL
You need to implement your own try/except block in the worker. Depending on how you want to organize your code, you could log to stderr as you mention above, log to some other place like a file, return some sort of error code or even tag the exception with the current traceback and re-raise. Here's an example of the last technique:
import traceback
import multiprocessing as mp
class MyError(Exception):
pass
def worker():
try:
# your real code here
raise MyError("boom")
except Exception, e:
e.traceback = traceback.format_exc()
raise
def main():
pool = mp.Pool()
try:
print "run worker"
result = pool.apply_async(worker)
result.get()
# handle exceptions you expect
except MyError, e:
print e.traceback
# re-raise the rest
except Exception, e:
print e.traceback
raise
if __name__=="__main__":
main()
It returns
run worker
Traceback (most recent call last):
File "doit.py", line 10, in worker
raise MyError("boom")
MyError: boom