pygal on windows - cannot access classes from pygal - python

I have such short script:
import pygal
if __name__ == '__main__':
bar_chart = pygal.Bar()
and following error: AttributeError: 'module' object has no attribute 'Bar'
Do you have any idea what is wrong? Shall I configure some additional paths? I am using windows.
Thank you

If your script is named pygal.py, when you import pygal, it's going to import your script, not the pygal library you installed into your system site-packages. And your script obviously doesn't have a class named Bar.
The solution is simple: rename your script to something different. Like pygaltest.py or mypygal.py.
And make sure to look at the directory and see if there's a pygal.pyc left behind, which Python compiled from your pygal.py. If so, you have to delete that file.

Related

Import on shared object fails with ModuleNotFound only when script is executed from command line

ran into a weird problem where there is a shared-object import error only when I run the script from command line. It succeed if i run the script in the python console using exec(...)
I have a class that needs a shared object: foo.py:
import os
cur_dir = os.curdir()
os.chdir('/tmp/dir_with_shared_object/')
import shared_object_class
os.chdir(cur_dir)
class Useful:
... # use the shared object import
Then there is a script like this:
from foo import Useful
If I enter python console and run:
exec(open('script.py').read())
Everything works fine.
If I run this on command line:
python script.py
I will get
ModuleNotFoundError: No module named 'shared_object_class'
The python is the same. It is 3.7.3, GCC 7.3.0 Anaconda. Anyone knows what is causing this discrepancy in behavior for shared object import?
A standard way of importing from a custom directory would be to include it in the PYTHONPATH environmental variable, with export PYTHONPATH=/tmp/dir_with_shared_object/.
update
It could also be done dynamically with
import sys
p = '/tmp/dir_with_shared_object/'
sys.path.insert(0, p)
PS
I think I have an explanation for why OP's original code didn't work. According to this python reference page, the import system searches, inter alia, in "[t]he directory containing the input script (or the current directory when no file is specified)." So the behavior in the REPL loop is different from how it is when running a script. Apparently the current directory is evaluated each time an import statement is encountered, while the directory containing the input script doesn't change.

Getting error "Module 'turtle' has no 'TurtleScreen' member"

I am getting an error while writing the Python program using the turtle module in VS Code:
"Module 'turtle' has no 'TurtleScreen' member"
Instead of the functional interface:
import turtle
wn = turtle.TurtleScreen()
Use the object-oriented interface:
from turtle import Screen, Turtle
wn = Turtle()
wn.TurtleScreen()
You have 2 problems.
First, you named your file turtle.py. This shadows the actual turtle module, and Python will load your turtle.py instead of the actual turtle built-in module.
You can easily check this by printing the module __file__:
import turtle
print(turtle.__file__)
wn = turtle.TurtleScreen
$ python turtle.Turtl.py
/path/to/your/turtle.py
...
Because if you rename turtle.py to something else (myturtle.py), it should print out a path to the Python installation folder:
$ python turtle.Turtl.py
/usr/local/opt/python#3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/turtle.py
...
Second, what you are actually seeing in the VS Code Problems tab, is a pylint error about not finding the module you are importing. It's a common problem with VS Code and pylint. The fix depends on the module you are importing, but generally, you can tell PyLint where to look for modules.
One solution is making sure you activated or selected the correct Python environment in VS Code. I see you are using Python 3.9, so make sure VS Code is using that same Python installation as what you use to run your code:
Another solution is to add an init-hook option to VS Code's pylintArgs:
{
"python.linting.pylintArgs": [
"--init-hook",
"import sys; sys.path.insert(0, '/usr/local/Cellar/python#3.9/3.9.1_5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/')"
]
}
Specify the path to the folder containing the module.

Python module script.vis install

Really sorry for my novice question.
I am trying to install a module in python for neo4j but I got an error.
here is the import :
from scripts.vis import vis_network
from scripts.vis import draw
Here is the error:
ModuleNotFoundError: No module named 'scripts'
I have tried "pip install scripts"
Thanks in advance
ModuleNotFoundError simply means the Python interpreter couldn't find the module. I suggest that you read about python modules and packaging here.
I have looked at the source code you pointed to and it works perfectly fine. I suspect your paths are not well set up.
Make sure that in you are running importing scripts.vis in app.py, the directory structure looks like this:
./scripts
./scripts/__init__.py
./scripts/vis.py
....
./app.py #in app.py, you can import as 'from scripts.vis import x'
Here's what it looks on my system:
app.py is successfully able to make the import from vis sub-module. You can use a IPython notebook, that should work fine too.
If you want to visualize the graph in the python environment (Jupyter), you can try using neo4jupyter library. Here you will use neo4jupyter.draw to visualize the graph.
Install !pip install neo4jupyter
For example:
import neo4jupyter
neo4jupyter.init_notebook_mode()
from py2neo import Node
nicole = Node("Person", name="Nicole", age=24)
drew = Node("Person", name="Drew", age=20)
graph.create(nicole | drew)
options = {"Person": "name"}
neo4jupyter.draw(graph, options)
You may find this useful:
https://github.com/merqurio/neo4jupyter
https://nicolewhite.github.io/neo4j-jupyter/hello-world.html

'module' object has no attribute 'py' when running from cmd

I'm currently learning unittesting, and I have stumbled upon a strange error:
If I run my script from inside PyCharm, everything works perfectly. If I run it from my cmd.exe (as administrator), I get the following error:
This is my code:
import unittest
class TutorialUnittest(unittest.TestCase):
def test_add(self):
self.assertEqual(23,23)
self.assertNotEqual(11,12)
# function for raising errors.
def test_raise(self):
with self.assertRaises(Exception):
raise Exception`
Just remove the .py extension.
You are running your tests using the -m command-line flag. The Python documentation will tell you more about it, just check out this link.
In a word, the -m option let you run a module, in your case the unittest module. This module expect to receive a module path or a class path following the Python format for module path (using dots). For example, if you want to run the FirstTest class in the mytests module in a mypackage folder you would use the following command line:
python -m unittest mypackage.mytests.FirstTest
Assuming that you are running the previous command line from the parent folder of mypackage. This allows you to select precisely the tests you want to run (even inside a module).
When you add the .py extension, unittest is looking for a py object (like a module or a class) inside the last element of the module path you gave but, yet this object does not exist. This is exactly what your terminal error tells:
AttributeError: ’module’ object has no attribute ’py’
you can add at the bottom of your script:
if __name__ == "__main__":
unittest.main()
Then you can run python test_my_function.py normally

Run python script from python using different python

I have a software that has python 2.5.5. I want to send a command that would start a script in python 2.7.5 and then proceed with the script.
I tried using
#!python2.7.5
and http://redsymbol.net/articles/env-and-python-scripts-version/
But I cant get it to work...
In my python 2.5.5 I can execute script as
execfile("c:/script/test.py")
The problem is that the 2.7.5 has a module comtypes + few other. I dont know how to install it for my 2.5.5 so I'm trying to start a separate script and run it under python27. Now another reason why I want it its because I want to take the load off program. I have 2 heavy tasks to perform. The second task is the one that need comptypes so sending it to external shell/app would do perfect trick. Is there a way to do it ?
I wish I could just type run("C:/Python27/python.exe % C:/script/test,py")
Thanks, bye.
Little update. I try to run
import os
os.system("\"C:\Python27\python.exe\" D:\test\runTest.py")
But I'm getting a quick pop up and close window saying that
Import Error : no module named site...
This works if I run from external shell but not from here :(
So I've tried another approach this time to add modules to python... in any case I run this :
import os
import sys
sys.path.append("C:/python27")
sys.path.append("C:/Python27/libs")
sys.path.append("C:/Python27/Lib")
sys.path.append("C:/Python27/Lib/logging")
sys.path.append("C:/Python27/Lib/site-packages")
sys.path.append("C:/Python27/Lib/ctypes")
sys.path.append("C:/Python27/DLLs")
import PyQt4
print PyQt4
import comtypes
import logging
but it crashes with C error...
Runtime Error :
Program: c:\Pr...
R6034
An application has made attempt to load the C runtime library incorectly.
blablabla....
How can I import it ? Maybe if I can import it I can run it directly from my app rather than starting separate python...
Traceback (most recent call last):
File "<string>", line 18, in <module>
File "C:\Python27\Lib\site-packages\comtypes\__init__.py", line 22, in <module>
from ctypes import *
File "C:\Python27\Lib\ctypes\__init__.py", line 10, in <module>
from _ctypes import Union, Structure, Array
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.
Another update to isseu
so I run now
import os
os.system("start cmd {D:\test\runTest.py}")
now this works and he open CMD with c:\Python27 as directory but he dont run the file... any hitns how to fix it?
Use "raw" strings so that you don't need to escape as much; I think the backslashes are what was breaking your code since backslash is considered an escape character except in raw strings.
Also, use the subprocess module. It makes it easy to avoid manually making a safe command string (the module takes care of that for you). All you need to do is pass it a list of arguments.
Your code would then look something like this:
import subprocess
proc = subprocess.Popen([r"C:\Python27\python.exe", r"D:\test\runTest.py"])
# then either do this
proc.wait() # wait until the process finishes
# or this
while True:
# NOTE: do something else here
# poll the process until it is done
if proc.poll() is not None:
break # break out of loop
See subprocess docs for Python 2 here. Be sure to check if a feature was added after Python 2.5 (the 2.5 docs aren't available online anymore AFAIK).
UPDATE:
I just noticed that you tried to use the Python 2.7 libraries and modules in your 2.5 code. This probably won't work due to new features added after 2.5. But it got me thinking how you might be able to make 2.7 work.
It may be that your Python2.7 install can't find its libraries; this is probably why you get the error Import Error : no module named site. You can do something like the above and modify the PYTHONPATH environment variable before starting the subprocess, like this:
import os
import subprocess
paths = [r"C:\python27", r"C:\python27\libs", r"C:\python27\Lib\site-packages", r"C:\python27\DLLs"]
paths += os.environ.get('PYTHONPATH', '').split(os.pathsep)
env27 = dict(os.environ)
env27['PYTHONPATH'] = os.pathsep.join(paths)
proc = subprocess.Popen([r"C:\Python27\python.exe", r"D:\test\runTest.py"], env=env27)

Categories