Error with random in python 2.7 - python-2.7

i have error running this following code in python:
from random import randint
code = "%d%d%d" % (randint(1,9), randint (1,9), randint(1,9))
guess = raw_input(">")
guesses = 0
while guess != code and guesses < 10:
print "wrong"
guesses += 1
guess = raw_input(">")
when i run it in windowpowershell i got this error"ImportError: cannot import name random". i tried to reinstall python but it still not working. Can someone guide me through this? thank you!

this is not a bug with the code. I tried running the code with python 2.7 and it runs fine. The only reason you would get this error is if, in C:>Python27>lib, there is no random.py and random. You commented that you found those files in the python27 folder, make sure that they are inside the lib folder inside of python27. Also make sure that your path for python (in edit environment variables for your account on windows 10) is the new one since you said you reinstalled it.

If you have another file with the same name random as the default module you are trying to import, Python27 will try to import that first. This can cause all sorts of issues. Try using Python3 or rename random.py to something else. Also, you should not be creating new files in C:\Python27, create a new file C:\Test\test.py like so.

Related

how do i fix "No module named 'win32api'" on python2.7

I am trying to import win32api in python 2.7.9. i did the "pip install pypiwin32" and made sure all the files were intalled correctly (i have the win32api.pyd under ${PYTHON_HOME}\Lib\site-packages\win32). i also tried coping the files from C:\Python27\Lib\site-packages\pywin32_system32 to C:\Python27\Lib\site-packages\win32. I also tried restarting my pc after each of these steps but nothing seems to work! i still get the error 'No module named 'win32api''
Well, turns out the answer is upgrading my python to 3.6.
python 2.7 seems to old to work with outside imports (I'm just guessing here, because its not the first time I'm having an import problem)
hope it helps :)

redirecting python import to another module

I'm working on a large open source Python project, which has modules used by both the project and other projects. The goal is to move some of these modules out to a new "library" project that can then be imported by the original project and other projects.
To make this transition smooth, the thought was to copy the modules over to the new project, and have the original project then use the new import. However, to allow other project to have time to migrate later, the thought was to have the original module redirect the import.
For example, the usage is like this in repo 'neutron' (other projects could do the same):
cat neutron/consumer.py
from neutron.redirected import X
print(X)
The in the new 'neutron_lib' project created, the module looks like this (the same as what the original was in project 'neutron'):
cat ../neutron-lib/neutron_lib/redirected.py
X = 5
In the 'neutron' project, I'm trying to do this as the redirect module:
cat neutron/redirected.py
import neutron_lib.redirected
import sys
sys.modules['neutron.redirected'] = neutron_lib.redirected
When I run pylint, it gives these errors:
************* Module neutron.redirected
E: 1, 0: No name 'redirected' in module 'neutron_lib' (no-name-in-module)
************* Module neutron.consumer
E: 1, 0: No name 'X' in module 'neutron.redirected' (no-name-in-module)
If I run this, it runs fine, and consumer.py prints '5'. If I use ipython and load consumer.py, I can see 'X' in dir() output.
Any idea why I'm getting this pylint error? Is it a false error? Is there a way to override it?
Looks like, when running under tox, I can add the following to .pylintrc to hide the errors/warnings
no-name-in-module
nonstandard-exception
When I run pylint it passes now, as does running the Unit tests. Just wish I understood why I'm getting these errors/warnings though.

py2exe can't find msvcp90.dll

I'm working on converting a simple GUI script written with Python 2.7 and Pyqt4 into a standalone executable using py2exe. I keep getting "no such file exists" errors, and I've managed to fix a few, though this one seems stubborn. It can't find msvcp90.dll, and returns an error message with a short traceback to distutils and then back to my py2exe script, which isn't very enlightening.
I've installed the MS C++ redistributable runtime, as recommended in
py2exe fails to generate an executable
but my script still can't locate the .dll. Below is my py2exe script, with the name of my script blocked out:
from distutils.core import setup
from py2exe.build_exe import py2exe
import sys, os, zmq
sys.argv.append('py2exe')
os.environ["PATH"] = \
os.environ["PATH"] + \
os.path.pathsep + os.path.split(zmq.__file__)[0]
setup(
options = {'py2exe':{'bundle_files':1,"includes":["zmq.utils",
"zmq.utils.jsonapi","zmq.utils.strtypes"]}},
console = [{'script':"#######.py"}],
zipfile = None
)
I've already fixed an issue with zmq (which isn't ever used by my script, or my GUI, for that matter, as far as I know). What am I doing wrong?
Right, I've managed to get my app to build, and although the question is now moderately old, it's my hope this is eventually of use to someone.
Firstly, py2exe is probably the wrong tool. It's old and AFAICT unmaintained. Consider PyInstaller instead. Using PyInstaller is literally as simple as installing it, installing PyWin32, and then going python %path_to_pyinstaller%/pyinstaller.py --onefile --windowed source.py. PyInstaller deals with all the mess of side by side assemblies and so on without you having to do anything.
In short, use PyInstaller.
However, to answer your question, this worked for me:
The question you've linked to - in particular this answer is the right start. Find the right DLLs and copy them to C:\Python27\DLLs
Ditch your existing setup.py file. If you're not using zmq, there's no reason to import it. Also, for a windowed application you want windows= not console=. My file goes (for packaging show.py):
#!/usr/bin/python
from distutils.core import setup
import py2exe
setup(options={'py2exe':{'bundle_files':1}},
windows=['show.py'])
(This is pinched off http://www.blog.pythonlibrary.org/2010/07/31/a-py2exe-tutorial-build-a-binary-series/)

How to run neato from pygraphviz on Windows

I am trying to use pygraphviz and networkx in python (v 2.7) to create a network map. I found a script that looks very useful on stackoverflow:
import networkx as nx
import numpy as np
import string
import pygraphviz
dt = [('len', float)]
A = np.array([(0, 0.3, 0.4, 0.7),
(0.3, 0, 0.9, 0.2),
(0.4, 0.9, 0, 0.1),
(0.7, 0.2, 0.1, 0)
])*10
A = A.view(dt)
G = nx.from_numpy_matrix(A)
G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())),string.ascii_uppercase)))
G = nx.to_agraph(G)
G.node_attr.update(color="red", style="filled")
G.edge_attr.update(color="blue", width="2.0")
G.draw('/tmp/out.png', format='png', prog='neato')
I get an error on the last line, basically it cannot find neato:
"ValueError: Program neato not found in path."
The error refers to the agraph.py file for pygraphviz, but I cannot see anything that could be causing the problem when I look through agraph.py
Any ideas how to resolve this? I am using windows and IDLE for my coding.
Thanks!
I had the same problem. Here's what I did in case anyone else is struggling to get pygraphvis working on Windows.
First off, I installed graphviz. I tried to install pygraphvis thrugh pip, but it refused to work. Eventually, I found the unofficial Windows binaries, so I installed that. Importing the module now works, but calling G.layout() led to the above error.
Calling neato -V worked, so it was on my PATH. I figured out that the problem was that python was running in a command prompt that was created prior to installing pygraphvis, so PATH wasn't updated. Restarting the command prompt fixed this, but led to a new error, something about C:\Program not being a valid command.
I figured that pygraphvis was probably failing to quote the path correctly, meaning it cuts off at the space in Program Files. I solved the problem by symlinking it to a path without spaces.
mklink /d C:\ProgramFilesx86 "C:\Program Files (x86)"
Note that this must be run in admin mode. You can do it by going to the start menu, typing in cmd, and then hitting Ctrl+shift+enter.
After this, I edited my PATH to refer to the symlink, restarted cmd, and everything worked.
The problem is that pygraphviz call an external program, a part of the graphviz suite called neato, to draw the graph. What is happening is that you doesn't have graphviz installed and when python try to call it it complains about not finding it. Actually pygraphviz is just a wrapper that gives you the possibility to call graphviz from inside python, but per se doesn't do anything and doesn't install graphviz by default.
The easiest solution is to try a different solution for the plot instead of neato. the accepted option are:
neato
dot
twopi
circo
fdp
nop
try one of those and see if one of them works. Otherwise you can install graphviz, that will give you the required program. It's and open-source program available on every platform, so it shouldn't be a problem to install it.
see at http://www.graphviz.org/
If you simply need to have a sketch of the graph you can use the networkx.draw function on a networkx graph, that uses matplotlib to create an interactive plot.
import networkx as nx
G = G=nx.from_numpy_matrix(A)
nx.draw(G)
Your problem is that neato is missing.
neato is part of the graphviz suite which you can install on your PC e.g. from here. (I used the .msi)
Now neato is "installed", but your system does not know where. So add the directory where neato.exe is contained in to your PATH environment variable. On Win10, this can be done with Start -> Edit environment variables for your account -> select path in the upper window -> edit -> New -> C:\Program Files (x86)\Graphviz2.38\bin\
or whatever your install directory is.
There is probably more than one cause for this error, but if it is caused by a missing path to the graphviz modules [neato,dot,twopi,circo,fdp,nop], then there is one hack that worked for me. I'm currently asking what the correct solution is, but you can use this
if not 'C:\\Program Files (x86)\\Graphviz2.38\\bin' in os.environ["PATH"]:
os.environ["PATH"] += os.pathsep + 'C:\\Program Files (x86)\\Graphviz2.38\\bin'
at the beginning of your script. To generalize, if your graphviz files are saved somewhere else:
graph_path='your_bin_folder_path'
if not graph_path in os.environ["PATH"]:
os.environ["PATH"] += os.pathsep + graph_path
In particular, this worked on windows 10, using anaconda navigator and python version 3.7.
Try something like this to see where pygraphviz thinks your external programs are:
# Get paths of graphviz programs
import pygraphviz as pgv
A = pgv.AGraph()
progs_list = ['neato', 'dot', 'twopi', 'circo', 'fdp', 'nop', 'wc', 'acyclic', 'gvpr',
'gvcolor', 'ccomps', 'sccmap', 'tred', 'sfdp', 'unflatten']
for prog in progs_list:
try:
runprog = A._get_prog(prog)
print(f'{runprog}')
except ValueError as e:
print(f'{prog} gets this error: {str(e).strip()}')
After looking at the results, it's a lot of work outside your IDE installing Graphviz and setting up your Path environmental variable in the System control panel, etc.

Django Gramps no module named web.settings

I'm using Gramps 3.3.1 under Ubuntu 12.04 and trying to in Django Export/Import. The install is okay, but when I look at the installed addons, it says that it failed, with reason: "No module named web.settings".
I cann't for the life of me figure out how to fix this. I'm assuming that it's this line in the python script:
import web.settings as default_settings
Anyone have any ideas? I'm trying to get this data out and into a MySQL database, but I can't seem to.
Thanks!
When you run into an error where Python tells you "No module named blah" it really means it can't find "blah".
I would check your pythonpath and the filesystem permissions on the stuff in your path.
Edit
Your issue seems to be a known issue: http://www.gramps-project.org/bugs/view.php?id=5464
It's caused by not running Gramps from source, near as I can tell. It doesn't look like a Python Path issue, so much as the Gramps Django devs making assumptions where your Django settings would be (but I could be wrong).
As for Python Path, there's plenty of resources describing how to. The simplest way to check your Python path is to run echo $PYTHONPATH in a terminal. If you don't see it there, Python might not find it.