python 3 - subtle import error - python-2.7

I am having tricky ImportError when packaging some modules, to try and support both python 2.7 and 3.6. There is nothing inside the code that's fancy to exlude one of these versions, so I thought I would try. The repo is at https://github.com/raamana/neuropredict
It worked fine before on 2.7 alone. To support both 2.7 and 3.6,
After much googling and head-scracting, I thought I figured out how to do that with the following import code at the top of each of the modules in my package:
from sys import version_info
if version_info.major==2 and version_info.minor==7:
import rhst, visualize
from freesurfer import aseg_stats_subcortical, aseg_stats_whole_brain
import config_neuropredict as cfg
elif version_info.major > 2:
from neuropredict import rhst, visualize
from neuropredict.freesurfer import aseg_stats_subcortical, aseg_stats_whole_brain
from neuropredict import config_neuropredict as cfg
else:
raise NotImplementedError('neuropredict supports only 2.7 or Python 3+. Upgrade to Python 3+ is recommended.')
The directory structure is :
$ 22:19:54 miner neuropredict >> tree
.
├── config_neuropredict.py
├── freesurfer.py
├── __init__.py
├── __main__.py
├── model_comparison.py
├── neuropredict.py
├── rhst.py
├── test_rhst.py
└── visualize.py
The init.py looks like this:
__all__ = ['neuropredict', 'rhst', 'visualize', 'freesurfer',
'config_neuropredict', 'model_comparison']
from sys import version_info
if version_info.major==2 and version_info.minor==7:
import neuropredict, config_neuropredict, rhst, visualize, freesurfer, model_comparison
elif version_info.major > 2:
from neuropredict import neuropredict, config_neuropredict, rhst, visualize, freesurfer, model_comparison
else:
raise NotImplementedError('neuropredict supports only 2.7 or Python 3+. Upgrade to Python 3+ is recommended.')
So when I run the unit tests locally or on CI, it works fine with above import mechanism.
$ 22:19:25 miner neuropredict >> pytest test_rhst.py
=============================================================================================== test session starts ===============================================================================================
platform linux -- Python 3.6.1, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: /data1/strother_lab/praamana/neuropredict, inifile:
plugins: hypothesis-3.23.2
collected 1 item
test_rhst.py .
============================================================================================ 1 passed in 8.73 seconds =============================================================================================
$ 22:19:42 miner neuropredict >>
However, when I run neuropredict.py directly, it thrown an error
$ 22:19:57 miner neuropredict >> python ./neuropredict.py
Traceback (most recent call last):
File "neuropredict.py", line 23, in <module>
from neuropredict import rhst, visualize
File "/data1/strother_lab/praamana/neuropredict/neuropredict/neuropredict.py", line 23, in <module>
from neuropredict import rhst, visualize
ImportError: cannot import name 'rhst'
$ 22:29:39 miner neuropredict >> pwd
/data1/strother_lab/praamana/neuropredict/neuropredict
$ 22:29:43 miner neuropredict >>
This is killing me - I need figure out where I am making a mistake, or if I am doing something sacrilegious.
Question 1: why am I not able to
python ./neuropredict.py
and get some parser help, when the test scripts can import it successfully? This used to work in many other scenarios. Driving me crazy as I can't understand what the hell is going on.
This is what I need to be able to achieve:
import config_neuropredict.py into all other modules
import config_neuropredict, rhst, visualize, freesurfer, model_comparison into the neuropredict.py module
make this reliably work in Python 3+ (2.7 support not important)
understand python's behaviour during Question 1 above.
If you need more details or into the code, I would appreciate if you can quickly head over to this public repo: https://github.com/raamana/neuropredict

Related

ImportError: cannot import name 'load_mnist' from 'pytorchcv'

---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-2cacdf187bba> in <module>
6 import numpy as np
7
----> 8 from pytorchcv import load_mnist, train, plot_results, plot_convolution, display_dataset
9 load_mnist(batch_size=128)
ImportError: cannot import name 'load_mnist' from 'pytorchcv' (/anaconda/envs/py37_pytorch/lib/python3.7/site-packages/pytorchcv/__init__.py)
How can fix this bug?
I use python 3.7 and Jupiter notebook. The code in Pytorch Fundamental of Microsoft: Link https://learn.microsoft.com/en-gb/learn/modules/intro-computer-vision-pytorch/5-convolutional-networks
import torch
import torch.nn as nn
import torchvision
import matplotlib.pyplot as plt
from torchinfo import summary
import numpy as np
from pytorchcv import load_mnist, train, plot_results, plot_convolution, display_dataset
load_mnist(batch_size=128)
I installed PyTorch by command: pip install pytorchcv
I assume you might have the wrong pytorchcv package. The one in pypy does not contain load_mnist
Starting from scratch you could download mnist as such:
data_train = torchvision.datasets.MNIST('./data',
download=True,train=True,transform=ToTensor()) data_test = torchvision.datasets.MNIST('./data',
download=True,train=False,transform=ToTensor())
They missed one command before importing pytorchcv.
This pytorchcv is different from pytorchcv in PyPI.
Run this before importing pytorchcv.
!wget https://raw.githubusercontent.com/MicrosoftDocs/pytorchfundamentals/main/computer-vision-pytorch/pytorchcv.py
Then it should work.
please download the prepared py file from the link https://raw.githubusercontent.com/MicrosoftDocs/pytorchfundamentals/main/computer-vision-pytorch/pytorchcv.py and put it into current folder, then VS Code could recognize it

Python 2.7 cannot find module in its search path

I wanted to test the relative import model of Python 2.X
Directory tree:
exercises/
dir1/
dir2/
mod.py
dir3/
mod2.py
mod3.py
mod.py
import sys
print 'in dir1/dir2/mod.py'
path = [name for name in sys.path if 'Frameworks' not in name].
print 'Module search path of mod is:\n' + str(path)
import dir3.mod2
mod2.py
print 'in dir1/dir2/dir3/mod2.py'
import mod3
mod3.py
print 'in dir1/dir2/dir3/mod3.py by relative import'
'mod' would import 'mod2' from 'dir3', which would then import 'mod3'. In Python 3.X, this would fail because the path to 'mod3' is not provided; in Python 2.X, the interpreter searches the same directory containing 'mod2' before searching the rest of the path starting from the top level directory of 'mod'.
This is the error message I get:
MacBook-Pro-9 exercises % python dir1/dir2/mod.py
in dir1/dir2/mod.py
Module search path of mod is:
['Users/arthur/Desktop/learning_python/exercises/dir1/dir2', '/Library/Python/2.7/site-packages']
Traceback (most recent call last):
File "Desktop/learning_python/exercises/dir1/dir2/mod.py", line 8, in <module>
import dir3.mod2
ImportError: No module named dir3.mod2
I know 'dir2' contains 'dir3/mod2', but for some reason, Python can't find it. I'm pretty sure that the syntax for the import statement is correct.
I modified the print statements and changed 'mod2.py' code to read from . import mod3. I edited nothing else, and it ran just fine in Python 3.8 There was no problem finding 'dir3.mod2'
You have to add an empty file inside dir3 named init.py for python to be able to recognize the directory as a Python package directory. If you have these files
dir3/__init__.py
dir3/mod2.py
dir3/mod3.py
You can now import the code in mod2.py and mod3.py as
import dir3.mod2
import dir3.mod3
or
from dir3 import mod2
from dir3 import mod3
If you remove the init.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
Here is the a link.

Using Sphinx autodoc to document Flask app

I am having problems in using Sphinx to generate documentation for a Flask app. Without going into specific details of the app its basic structure looks as follows.
__all__ = ['APP']
<python 2 imports>
<flask imports>
<custom imports>
APP = None # module-level variable to store the Flask app
<other module level variables>
# App initialisation
def init():
global APP
APP = Flask(__name__)
<other initialisation code>
try:
init()
except Exception as e:
logger.exception(str(e))
#APP.route(os.path.join(<service base url>, <request action>), methods=["POST"])
<request action handler>
if __name__ == '__main__':
init()
APP.run(debug=True, host='0.0.0.0', port=5000)
I've installed Sphinx in a venv along with other packages needed for the web service, and the build folder is within a docs subfolder which looks like this
docs
├── Makefile
├── _build
├── _static
├── _templates
├── conf.py
├── index.rst
├── introduction.rst
└── make.bat
The conf.py was generated by running sphinx-quickstart and it contains the line
autodoc_mock_imports = [<external imports to ignore>]
to ensure that Sphinx will ignore the listed external imports. The index.rst is standard
.. myapp documentation master file, created by
sphinx-quickstart on Fri Jun 16 12:35:40 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to myapp's documentation!
=============================================
.. toctree::
:maxdepth: 2
:caption: Contents:
introduction
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
and I've added an introduction.rst page to document the app members
===================
`myapp`
===================
Oasis Flask app that handles keys requests.
myapp.app
---------------------
.. automodule:: myapp.app
:members:
:undoc-members:
When I run make html in docs I am getting HTML output in the _build subfolder but I get the following warning
WARNING: /path/to/myapp/docs/introduction.rst:10: (WARNING/2) autodoc: failed to import module u'myapp.app'; the following exception was raised:
Traceback (most recent call last):
File "/path/to/myapp/venv/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 657, in import_object
__import__(self.modname)
File "/path/to/myapp/__init__.py", line 4, in <module>
from .app import APP
File "/path/to/myapp/app.py", line 139, in <module>
#APP.route(os.path.join(<service base url>, <request action>), methods=['GET'])
File "/path/to/myapp/venv/lib/python2.7/posixpath.py", line 70, in join
elif path == '' or path.endswith('/'):
AttributeError: 'NoneType' object has no attribute 'endswith'
and I am not seeing the documentation I am expecting to see for the app members like the request handler and the app init method.
I don't know what the problem is, any help would be appreciated.
Try using sphinx-apidoc to automatically generate Sphinx sources that, using the autodoc extension, document a whole package in the style of other automatic API documentation tools. You will need to add 'sphinx.ext.autodoc' to your list of Sphinx extensions in your conf.py, too.

ImportError with nltk_train

I am trying to get my ways around with nltk-trainer (https://github.com/japerk/nltk-trainer). I managed to train Dutch taggers and chunkers with the commands (directly in Anaconda console):
python train_tagger.py conll2002 --fileids ned.train --classifier IIS --filename ~/nltk_data/taggers/conll2002_ned_IIS.pickle
python train_chunker.py conll2002 --fileids ned.train --classifier NaiveBayes --filename ~/nltk_data/chunkers/conll2002_ned_NaiveBayes.pickle
Then I run a little script to test the tagger and the chunker:
import nltk
from nltk.corpus import conll2002
# Loading training pickles
tokenizer = nltk.data.load('tokenizers/punkt/dutch.pickle')
tagger = nltk.data.load('taggers/conll2002_ned_IIS.pickle')
chunker = nltk.data.load('chunkers/conll2002_ned_NaiveBayes.pickle')
# Testing
test_sents = conll2002.tagged_sents(fileids="ned.testb")[0:1000]
print "tagger accuracy on test-set: " + str(tagger.evaluate(test_sents))
test_sents = conll2002.chunked_sents(fileids="ned.testb")[0:1000]
print "tagger accuracy on test-set: " + str(chunker.evaluate(test_sents))
This works fine from the nltk-trainer-master folder, but when I move the script elsewhere, I get an import error:
ImportError: No module named nltk_trainer.chunking.chunkers
How can I make this work outside the nltk-trainer-master folder, without copying the nltk_trainer folder?
(Python 2.7, nltk 3.2.1)

Python packaging can't import class handler

I have two packages (diretories ) in my Python project
src
/textmining
mining.py...def mining():#...
__init.py....__all__ = ["mining"]
/crawler
crawler.py
in crawler.py I use the mining class
mining=mining()
main.py
__init__.py
my main.py is as follow:
scrapy_command = 'scrapy runspider {spider_name} -a crawling_level="{param_1}"'.format(spider_name='crawler/crawler.py',
param_1=crawling_level)
process = subprocess.Popen(scrapy_command, shell=True)
when I run crawler, it prompts
runspider: error: Unable to load 'Crawler.py': cannot import name mining
You need an __init__.py in every folder that's a part of the same package module.
src
__init__.py
/textmining
__init__.py
mining.py
/crawler
__init__.py
crawler.py
For simplicity, you should add a main.py in the src folder and call the function you want to start your program with from there as it's fairly difficult to import modules from sibling directories if you start your script in a non-root directory.
main.py
from crawler import crawler
crawler.start_function()
crawler.py
from src.textmining import mining
miner = mining()
Without turning everything into a python module you'd have to import a folder into the current script or __init__.py module by adding to path:
# In crawler.py
import sys
import os
sys.path.append(os.path.abspath('../textmining'))
import mining
However, messing around with the path requires you to keep in mind what you've done and may not be a thing you desire.