This is a 2-part question and the first part is simple. I'm trying to get the current time as a high resolution number, something easily done with the Time::HiRes module in perl. I did find answers this questions elsewhere to use using time.time() in python. The only thing is when I do this all I get as 2 significant digits and am wondering if I need to import something else or set something in my environment or what. Look at this:
>>> import time
>>> print time.time()
1326459121.68
My second question has to do with setitimer, which according to the docs says it will deliver alarms and the time can be specified as a floating point number. Sounds exactly what I want. In fact, according to this - python timer mystery it looks pretty easy to use. But when I make an exact copy of that example, I get this:
[root#poker python]# ./signal.py
Traceback (most recent call last):
File "./signal.py", line 10, in ?
signal.setitimer(signal.ITIMER_REAL, 2, 2)
AttributeError: 'module' object has no attribute 'setitimer'
Perhaps part my the problem is that as a new python user I'm still not 'one with python' and perhaps am not understanding what the error message it trying to tell me. Is it complaining that it can't find signal.setitimer OR is there something wrong with the attributes I'm passing? I was wondering if it couldn't resolve signal.ITIMER_REAL and so tried calling it with a 0 just to see what would happen and now it's telling me:
[root#poker python]# ./signal.py
Traceback (most recent call last):
File "./signal.py", line 10, in ?
signal.setitimer(0, 2, 2)
AttributeError: 'module' object has no attribute 'setitimer'
so I have to believe it is signal.setitmer itself that is having issues.
Aha! I just figured out the problem by trying this on a VM with a newer version of python and it works just fine. Looks like setitimer is not available with my version of python but how can I tell from the error message? Shouldn't it be saying the module has no method? Calling the missing method an attribute is pretty confusing.
Maybe that's just part of the learning curve. Anyhow I thought I'd keep this second question in here so other might benefit, but I still am still stumped by what I can't get high resultion time from time.time() which still only reports in hundredths of a second even on this newer version of python.
time.time() returns more digits but the repr truncates to 2.
>>> import time
>>> time.time()
1326460396.626451
>>> print time.time()
1326460422.68
The problem with not being able to find setitimer is quite simply because you've named your python script 'signal.py', when you 'import signal' in your script, you're actually importing your script -- not the signal module. Just rename it to something else and it'll work.
Related
I'm trying to get the ODB library working. In the documentation at https://python-obd.readthedocs.io/en/latest/ it lists the following code:
import obd
connection = obd.OBD("/dev/ttyUSB0") # connects to USB or RF port
cmd = obd.commands.SPEED # select an OBD command (sensor)
response = connection.query(cmd) # send the command, and parse the response
print(response.value) # returns unit-bearing values thanks to Pint
print(response.value.to("mph")) # user-friendly unit conversions
When I put this in a file called test.py and I run it:
python2 test.py
I get the following error message:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import obd
File "/home/ubuntu/obd.py", line 3, in <module>
AttributeError: 'module' object has no attribute 'OBD'
Stackoverflow comes up with several iterations of this error message, but none clearly explain the problem, only giving specific solutions to those libraries.
I guess it's obvious that I'm new to Python, and I'm having trouble interpreting this error message, even after several hours of writing several small Python programs. I am of course also interested in why the error message is so un-intuitive to a newcomer and where I can gain the common knowledge I might be missing, and I guess this is as good a case to discover that through as any.
So far I have figured out the following:
<module> refers to the name of my python script that I am trying to run.
The mistake I made at first, was to name my test.py file, initially obd.py. This conflicted with the import obd as it was trying to import the file itself - even after I deleted it! The reason was that when I tried to run it the first time, it created a file called obd.pyc - and even though obd.py was no longer there, import OBD found the initially created obd.pyc and tried to import that - which of course does not contain the OBD object from the library I was trying to use.
This is not the detailed answer I'm looking for, so please add a more detailed explanation - or a link to how Python compiling works, if you can.
I am wondering if it is possible to edit/customize the behavior and printout of built-in errors in Python. For example, if I type:
>>> a = 1
>>> print A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined
I want the output to instead be:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined. Check capitalization.
Moreover, I want this to occur at a global level, for ALL FUTURE CODE, without having to explicitly include an exception in my code. If such a change is possible, I would assume this needs to be done at the very source or library-file level of Python. However, I am not sure where exactly to look to know if this is even possible.
I am using Python 2.7 on both Ubuntu and OSX, so help on either system would be appreciated.
(My apologies in advance if this is covered elsewhere, but searching for threads on "changing Python error messages" generally gave me topics on Exceptions, which is not necessarily my interest here. If anyone can point me to a page on this though, I'd greatly appreciate it.)
YES! There is a way to exactly what you want!
traceback.py is the program that detects errors in your code. It then gives you an explanation of what happened (creates the error message that you see.)
You can find this file in your library folder for python.
When in that file you can change the messages that it outputs when you come across an error!
Please tell me if this helped you!
I was trying to use the os.mknod function in Python 3.5.0 in Windows 7, however I find the error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
os.mknod
AttributeError: module 'os' has no attribute 'mknod'
I guess it's supposed to be there, since https://docs.python.org/3/library/os.html doesn't say anything about limited availability. Is there another option to use for a similar function in Windows? I'm just looking to create an empty file in a specific path, and I was thinking calling open(path, 'w') is kinda ugly for this.
I don't know if this might be a version specific problem since I've never used Python in Windows before.
Since commit in 2016, this is now documented:
Availability: Unix.
I'm new here and on Python World (although learning kind of quickly...), and just stumbled uppon the same issue.
My suggestion: for now, I would just go with the following and turn a blind eye on it...
with open('name_your_file.extention', 'w') as an_alias_for_it:
pass
In the end, it's not neat, but will be naturally "portable" among POSIX and NT systems.
I'm interested in experimenting with python. I know I can inspect and inject local and global variables into a frame using frame.f_locals and frame.f_globals, but I am now itching to create a full call stack.
What is keeping me from just changing the stack information is the fact that python doesn't allow me to change it.
I have actually considered programmatically transforming the python module I am using, in order to simulate winding the stack. But I am aware it is a terrible solution because client code usage of if, while, with and try would easily break my code.
I've also looked at manipulating frame.f_back, to no avail. It's read-only.
>>> import sys
...
... frm = sys._getframe()
...
... frm.f_back = None
Traceback (most recent call last):
File "<pyshell#4>", line 5, in <module>
frm.f_back = None
TypeError: readonly attribute
What I'm trying to do
As an experiment, I'm trying to implement fork() across a network.
I'm aware stackless python may have what I want, but it's still impossible to change the frame.f_back attribute.
Have a look on Online Python Tutor (http://www.pythontutor.com/). What it does is that it captures frames during execution to create visualization of python code. So, you could use the captured frames.
>>> type(sys._getframe())()
TypeError: cannot create 'frame' instances
Sorry.
You should look at the AST module and the symtable module
I've come across a bug in Python (at least in 2.6.1) for the bytearray.fromhex function. This is what happens if you try the example from the docstring:
>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str
This example works fine in Python 2.7, and I want to know the best way of coding around the problem. I don't want to always convert to unicode as it's a performance hit, and testing which Python version is being used feels wrong.
So is there a better way to code around this sort of problem so that it will work for all versions, preferably without slowing it down for the working Pythons?
For cases like this it's good to remember that a try block is very cheap if no exception is thrown. So I'd use:
try:
x = bytearray.fromhex(some_str)
except TypeError:
# Work-around for Python 2.6 bug
x = bytearray.fromhex(unicode(some_str))
This lets Python 2.6 work with a small performance hit, but 2.7 shouldn't suffer at all. It's certainly preferable to checking Python version explicitly!
The bug itself (and it certainly does seem to be one) is still present in Python 2.6.5, but I couldn't find any mention of it at bugs.python.org, so maybe it was fixed by accident in 2.7! It looks like a back-ported Python 3 feature that wasn't tested properly in 2.6.
You can also create your own function to do the work, conditionalized on what you need:
def my_fromhex(s):
return bytearray.fromhex(s)
try:
my_fromhex('hello')
except TypeError:
def my_fromhex(s):
return bytearray.fromhex(unicode(s))
and then use my_fromhex in your code. This way, the exception only happens once, and during your runtime, the correct function is used without excess unicode casting or exception machinery.