'argparse' has no 'ArgumentParser' member - python

Python newbie question...
I am using Python3.6 on macOS and I have installed argpase using
sudo pip3 install argparse
pip3 list does not list argparse but I can see it is installed because "help("argparse") in python3 displays the documentation.
But when I write the following simple test program I receive the error: " 'argparse' has no 'ArgumentParser' member"
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
Ideas?
Thanks in advance

Based on the comments, we know that the issue was that the user created a file called argparse.py, which shadowed the standard library argparse. An easy way to detect if this is the case is to print out the file path location of a module.
>>> import argparse
>>> print(argparse.__file__)
>>> # alternatively you can use inspect
>>> import inspect
>>> print(inspect.getsourcefile(argparse))
This will show where the file is located. It would be easy to debug the problem when you see the file path that is being used.

Related

python-redfish: $HOME environment variable not set, please check your system

I tried to import the python lib called "redfish" but was in vain; I import another lib(os) first and seems ok:
>>> import os
>>> import redfish
$HOME environment variable not set, please check your systemPS
C:\Users\user>
I also checked the environment variable; I use Enthought Canopy as my python IDE:
And python is also added to system variable:
And then I used python console, tried to get HOME, but it shows nothing
I've searched for a while but no related issues when users import python redfish lib, maybe redfish is a new BMC standard so not widely-used currently for pyhton-users. Thanks in advance for any suggestions.
Finally, I found the path of redfish packages :
>>> import sys
>>> print '\n'.join(sys.path)
>>>..................................................
..................................................
C:\users\user\appdata\local\enthought\canopy\user
*C:\users\user\appdata\local\enthought\canopy\user\lib\site-packages*
and then add it to the system variable $HOME, and open python shell again to import the lib and it works.
>>> import os
>>> HOME = os.getenv('HOME')
>>> HOME
'C:/users/user/appdata/local/enthought/canopy/user/lib/site-packages/'
>>> import redfish
>>> redfish.connect
<function connect at 0x0000000003E6B898>
Run the following in the terminal
pip uninstall python-redfish
pip uninstall python
pip install python

Import python package after installing it with setup.py, without restarting?

I have a package that I would like to automatically install and use from within my own Python script.
Right now I have this:
>>> # ... code for downloading and un-targzing
>>> from subprocess import call
>>> call(['python', 'setup.py', 'install'])
>>> from <package> import <name>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named <package>
Then I can continue like this:
>>> exit()
$ python
>>> from <package> import <name>
And it works just fine. For some reason, Python is able to pick up the package just fine if I restart after running the setup.py file, but not if I don't. How can I make it work without having the restart step in the middle?
(Also, is there a superior alternative to using subprocess.call() to run setup.py within a python script? Seems silly to spawn a whole new Python interpreter from within one, but I don't know how else to pass that install argument.)
Depending on your Python version, you want to look into imp or importlib.
e.g. for Python 3, you can do:
from importlib.machinery import SourceFileLoader
directory_name = # os.path to module
# where __init__.py is the module entry point
s = SourceFileloader(directory_name, __init__.py).load_module()
or, if you're feeling brave that your Python path knows about the directory:
map(__import__, 'new_package_name')
Hope this helps,
I downloaded from seaborn from GitHub.
Through command prompt, cd to downloads\seaborn folder
python install setup.py
Then using spyder from anaconda, checked if it was installed by running the following in a console
import pip
sorted(["%s==%s" % (i.key, i.version)
for i in pip.get_installed_distributions()])
Seeing that it was not there, go to tools and select "Update module names list"
Again trying the previous code in a python console, the lib was still not showing.
Restarting Spyder and trying import seaborn worked.
Hope this helps.

how to use pip module to list versions on a server?

I'm trying to figure out how to use pip as a module. Specifically, I want to be able to query a local pypi server for available module version numbers.
I've learned, for example, I can do this to get a list of packages installed on my machine:
import pip
for dist in pip.get_installed_distributions():
print dist.key, dist.version
I want the equivalent, but for getting packages available on my own pypi server. Is there a good way to do that, or is pip not really designed to be used by anything other than the pip command line utility?
Ultimately what I'm trying to accomplish is to build in auto-update functionality to a program I'm writing, so I need to be able to get the version I have and the version that's available.
I'm looking for a solution for python 2.7.
You can use the command line pip list -o to list the outdated packages.
If you want to use it as a module, you have to replicate what pip is doing since it is expecting to be used from the command line. The following function will output a list of tuples ('package', 'current version', 'latest version') assuming that you only want to look on your local server
from StringIO import StringIO
import sys
import re
from pip import parseopts
from pip.commands import commands
def list_outdated(pypi_server):
args = ['list', '-o', '-f', pypi_server, '--no-index']
cmd_name, options, args, parser = parseopts(args)
command = commands['list'](parser)
_stdout = sys.stdout
output = StringIO()
sys.stdout = output
command.main(args, options)
sys.stdout = _stdout
return re.findall('(\w+)\s+\(Current:\s+(.*?) Latest:\s+(.*?)\)', output.read() * 2)
outdated = list_outdated('http://my_server:8080/packages/')

Using portable python to connect to an Access database

I am wanting to use portable python 2.7.x to connect to an Access database. I can't seem to get it working as it doesn't have the pyodbc libraries. Is there another way to use portable python to connect?
The newest version of portable python has an option to install pyodbc but you have to select the option it doesn't go in by default.
Click on the modules option
Select the option for pyodbc
I have did it in different way.. .
follow what i have just done on my mac snow leopard!!
Download the the pyodbc's source from where it is on internet.
Extract and 'cd' into that dir.. . Run 'python setup.py build' and then take 'pyodbc.so' file from that build's dir. Make new python file named as 'pyodbc.py' and write the content given below.(and put that 'pyodbc.so' file with it)
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__,'pyodbc.so')
__loader__ = None; del __bootstrap__, __loader__
imp.load_dynamic(__name__,__file__)
__bootstrap__()
(remember put above code in file named as 'pyodbc.py' and put that 'pyodbc.so' file with that)
and at last ..put all these where ever you want to use or in run time add that location into sys.path as:
>>> import sys
>>> sys.path.insert(0,"/my_portable/location") # location to dir which contains those two files
after doing all this i have put those two files with my test python file..and in that i am able to import 'pyodbc' without installing it.
>>> import pyodbc
>>> dir(pyodbc)

How do I automatically install missing python modules? [duplicate]

This question already has answers here:
How can I Install a Python module within code?
(12 answers)
Closed 6 years ago.
I would like to be able to write:
try:
import foo
except ImportError:
install_the_module("foo")
What is the recommended/idiomatic way to handle this scenario?
I've seen a lot of scripts simply print an error or warning notifying the user about the missing module and (sometimes) providing instructions on how to install. However, if I know the module is available on PyPI, then I could surely take this a step further an initiate the installation process. No?
Risking negative votes, I would like to suggest a quick hack. Please note that I'm completely on board with accepted answer that dependencies should be managed externally.
But for situations where you absolutely need to hack something that acts like self contained, you can try something like below:
import os
try:
import requests
except ImportError:
print "Trying to Install required module: requests\n"
os.system('python -m pip install requests')
# -- above lines try to install requests module if not present
# -- if all went well, import required module again ( for global access)
import requests
Installation issues are not subject of the source code!
You define your dependencies properly inside the setup.py of your package
using the install_requires configuration.
That's the way to go...installing something as a result of an ImportError
is kind of weird and scary. Don't do it.
try:
import foo
except ImportError:
sys.exit("""You need foo!
install it from http://pypi.python.org/pypi/foo
or run pip install foo.""")
Don't touch user's installation.
Here's the solution I put together which I call pyInstall.py. It actually checks whether the module is installed rather than relying on ImportError (it just looks cleaner, in my opinion, to handle this with an if rather than a try/except).
I've used it under version 2.6 and 2.7... it would probably work in older versions if I didn't want to handle print as a function... and I think it'll work in version 3.0+ but I've never tried it.
Also, as I note in the comments of my getPip function, I don't think that particular function will work under OS X.
from __future__ import print_function
from subprocess import call
def installPip(log=print):
"""
Pip is the standard package manager for Python. Starting with Python 3.4
it's included in the default installation, but older versions may need to
download and install it. This code should pretty cleanly do just that.
"""
log("Installing pip, the standard Python Package Manager, first")
from os import remove
from urllib import urlretrieve
urlretrieve("https://bootstrap.pypa.io/get-pip.py", "get-pip.py")
call(["python", "get-pip.py"])
# Clean up now...
remove("get-pip.py")
def getPip(log=print):
"""
Pip is the standard package manager for Python.
This returns the path to the pip executable, installing it if necessary.
"""
from os.path import isfile, join
from sys import prefix
# Generate the path to where pip is or will be installed... this has been
# tested and works on Windows, but will likely need tweaking for other OS's.
# On OS X, I seem to have pip at /usr/local/bin/pip?
pipPath = join(prefix, 'Scripts', 'pip.exe')
# Check if pip is installed, and install it if it isn't.
if not isfile(pipPath):
installPip(log)
if not isfile(pipPath):
raise("Failed to find or install pip!")
return pipPath
def installIfNeeded(moduleName, nameOnPip=None, notes="", log=print):
""" Installs a Python library using pip, if it isn't already installed. """
from pkgutil import iter_modules
# Check if the module is installed
if moduleName not in [tuple_[1] for tuple_ in iter_modules()]:
log("Installing " + moduleName + notes + " Library for Python")
call([getPip(log), "install", nameOnPip if nameOnPip else moduleName])
Here are some usage examples:
from datetime import datetime
from pyInstall import installIfNeeded
# I like to have my messages timestamped so I can get an idea of how long they take.
def log(message):
print(datetime.now().strftime("%a %b %d %H:%M:%S") + " - " + str(message))
# The name fabric doesn't really convey to the end user why the module is needed,
# so I include a very quick note that it's used for SSH.
installIfNeeded("fabric", notes = " (ssh)", log = log)
# SoftLayer is actually named softlayer on pip.
installIfNeeded("SoftLayer", "softlayer", log = log)
Edit: A more cross-platform way of getting pipPath is:
from subprocess import Popen, PIPE
finder = Popen(['where' if isWindows() else 'which', 'pip'], stdout = PIPE, stderr = PIPE)
pipPath = finder.communicate()[0].strip()
This makes the assumption that pip is/will be installed on the system path. It tends to be pretty reliable on non-Windows platforms, but on Windows it may be better to use the code in my original answer.

Categories