this simple python program that is extracted from more complex codebase:
#insp.py
import inspect
L = lambda x: x+1
print("L(10)=" + str(L(10)))
code = inspect.getsource(L)
print(code)
works if i run it from the command line as:
$ python insp.py
If I copy and paste each line in the python interpreter it fails:
d:\>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> L = lambda x: x+1
>>> print("L(10)=" + str(L(10)))
L(10)=11
>>> code = inspect.getsource(L)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 944, in getsource
lines, lnum = getsourcelines(object)
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 931, in getsourcelines
lines, lnum = findsource(object)
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 762, in findsource
raise OSError('could not get source code')
OSError: could not get source code
Note that using IPython instead of the plain Python interpreter, it works!
Does anybody know why?
I use Python 3.5 32 bits under Windows7.
It works in IPython because it caches each and every command you enter there using linecache module.
For example:
$ ipy ## Equivalent to ipython --classic
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
Type "copyright", "credits" or "license" for more information.
IPython 3.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
>>> print a
Traceback (most recent call last):
File "<ipython-input-1-9d7b17ad5387>", line 1, in <module>
print a
NameError: name 'a' is not defined
Notice the <ipython-input-1-9d7b17ad5387> part here, this is something specific to IPython. In normal Python shell you would see <stdin>:
$ python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
Now let's run your code:
>>> import inspect
>>> L = lambda x: x+1
>>> code = inspect.getsource(L)
Time to find out the filename related to L:
>>> L.func_code.co_filename
'<ipython-input-2-0c0d6f325784>'
Now let's see if we have the source in linecache.cache for this file:
>>> import linecache
>>> linecache.cache[L.func_code.co_filename]
(18, 1481047125.479239, [u'L = lambda x: x+1\n'], '<ipython-input-2-0c0d6f325784>')
So, using this information IPython is able to find the required source but Python shell doesn't because it is not storing any.
The related details about how inspect gets the source can be found in getsourcefile and findsource functions in the source code.
Related
I am using Paraview 4.0.1 under Ubuntu 14.04 LTS.
But I guess the answer to this question does not necessarily requires knowledge specific to Paraview python.
When I load a python prompt at the command line everything "works well":
$ pvpython
Python 2.7.6 (default, Oct 26 2016, 20:33:43)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from paraview.simple import *
paraview version 4.0.1
>>>
But when I load the python shell within the GUI, from paraview.simple import * fails, either when automatically (at startup) or explicitly imported:
Python 2.7.6 (default, Oct 26 2016, 20:33:43)
[GCC 4.8.4] on linux2
from paraview.simple import *
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/paraview/simple.py", line 41, in <module>
import servermanager
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 3157, in <module>
__initialize()
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 3148, in __initialize
c = Connection(iter.GetCurrentSessionId(), iter.GetCurrentSession())
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 1935, in __init__
_createModules(self.Modules)
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 2567, in _createModules
m.filters = createModule('filters')
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 2629, in createModule
if (prop.GetInformationOnly() and propName != "TimestepValues" ) \
AttributeError: 'NoneType' object has no attribute 'GetInformationOnly'
>>> from paraview.simple import *
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 2190, in find_module
if vtkPVPythonModule.HasModule(fullname):
AttributeError: 'NoneType' object has no attribute 'HasModule'
>>>
How can I trace the different sequence of steps taken by each mode of loading a python shell, so as to identify the source of error?
In addition to this manifestation, I found two other differences:
In the command prompt, from paraview.simple import * is not executed automatically, while in the GUI it is. Where is this set?
In the command prompt, having set PYTHONSTARTUP=${HOME}/.pythonrc, which sets import readline, rlcompleter (actually, within a try-except construct), allows for tab completion.
In the GUI, .pythonrc is not read. Why is this? How can I tell the filename which would be read upon startup if it exists?
I have found one option which gives some information, I do not know if it is the only/best one.
Setting
$ export PYTHONVERBOSE=2
(or a different integer for verbosity level [1]) gives a lot of info.
Still, I couldn't find the source of error...
How to start a windows application like notepad using python NET ? This is my source code with python 2.7.13:
C:\Python27>python.exe
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> import System
>>> type = System.Type.GetTypeFromProgID("Notepad.Application")
>>> System.Activator.CreateInstance(type)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
System.ArgumentNullException: Value cannot be null.
Parameter name: activationContext
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
at System.Activator.CreateInstance(ActivationContext activationContext)
There is no ProgID="Notepad.Application" COM object on my machine, pythonnet works with other COM objects:
>>> import clr
>>> import System
>>> type1=System.Type.GetTypeFromProgID("Excel.Application")
>>> type1
<System.RuntimeType object at 0x02ABEE10>
>>> System.Activator.CreateInstance(type1)
<Microsoft.Office.Interop.Excel.ApplicationClass object at 0x02AD11D0>
I'm having problem with listing home directory of current user without knowing absolute path to it. I've tried with the following, but it doesn't work:
[root#blackbox source]# python
Python 2.6.6 (r266:84292, Dec 7 2011, 20:38:36)
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir('/root')
['python', '.bashrc', '.viminfo']
>>> os.listdir('~')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '~'
>>>
You need to use the os.path.expanduser() function:
>>> import os.path
>>> os.path.expanduser('~')
'/home/username'
You could ask the Operation System like this:
>>> import os
>>> os.environ['HOME']
'/home/noctua'
>>> os.listdir(os.environ['HOME'])
Running python on Snow Leopard, and I can't import the 'time' module. Works in ipython. Don't have any .pythonrc files being loaded. Scripts that 'import time' using the same interpreter run fine. Have no idea how to troubleshoot this. Anyone have an idea?
[wiggles#bananas ~]$ python2.6
Python 2.6.6 (r266:84292, Sep 1 2010, 14:27:13)
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "time.py", line 4, in <module>
t = now.strftime("%d-%m-%Y-%H-%M")
AttributeError: struct_time
>>>
[wiggles#bananas ~]$ ipython-2.6
Python 2.6.6 (r266:84292, Sep 1 2010, 14:27:13)
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import time
In [2]:
Look for a file called time.py. It looks like Python is importing that, instead of the one from the standard library:
File "time.py", line 4, in <module>
The solution is to rename the file something other than "time.py".
By the way, you can find the path to the offending file by opening a Python REPL and typing.
In [1]: import time
In [2]: time.__file__
or
In [3]: time # This shows the path as part of the repr
I have an error when i used pyqrcode.
[root#localhost python2.6]# python
Python 2.6.5 (r265:79063, Sep 7 2010, 07:31:57)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import qrcode
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/site-packages/qrcode-0.2.1-py2.6-linux-x86_64.egg/qrcode/__init__.py", line 6, in <module>
from qrcode import _qrcode
ImportError: cannot import name _qrcode
How to resolve above error?
I am referring pyqrcode from http://pyqrcode.sourceforge.net/
Thanks,
Manu
After the installation of PIL-1.1.7 and JCC-2.14, I've tried to install pyqrcode-0.2.1 from sources as you did, and also ran into the same error :
ImportError: No module named _qrcode. But then I've noticed that _qrcode is actually a lib (_qrcode.so). So I've tried to add it on my library path :
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/python2.7/site-packages/qrcode-0.2.1-py2.7-linux-x86_64.egg/qrcode/
And it worked ! Well actually, not quite, I ran into another error :
AttributeError: 'module' object has no attribute '_setExceptionTypes'
So I've edited the __init__.py file
# probably located under a path like this for linux
/usr/local/lib/python2.7/site-packages/qrcode-0.2.1-py2.7-linux-x86_64.egg/qrcode/
# or under a path like this for a Mac
/Library/Python/2.7/site-packages/qrcode-0.2.1-py2.7-macosx-10.7-intel.egg/qrcode/
and commented out line 21 :
# _qrcode._setExceptionTypes(JavaError, InvalidArgsError)
Then I was able to run their simple example :
#!/usr/bin/env python
# coding: utf-8
#
# pyqrcode sample encoder
import sys, qrcode
e = qrcode.Encoder()
image = e.encode('woah!', version=15, mode=e.mode.BINARY, eclevel=e.eclevel.H)
image.save('out.png')
(source : http://pyqrcode.sourceforge.net/)
Hope it helps,