Problems using Colorama on Python 2.7 - python-2.7

I'm learning to use colorama in Python, so I installed it and I'm able to import the module with no problems from the Primary Prompt.
>>> import colorama
>>> from colorama import *
>>> print(Fore.BLUE + 'BLUE TEXT')
BLUE TEXT
Now, if I create a small piece of code like this:
#!/usr/bin/env python2.7
from colorama import *
print(Fore.BLUE + 'BLUE TEXT')
I get the following message:
File "colorama_Test.py", line 3, in <module>
from colorama import *
File "/home/olg32/Python/colorama_Test.py", line 5, in <module>
print(Fore.BLUE + 'BLUE TEXT')
NameError: name 'Fore' is not defined
Which tells me that the module is not being found. But as mentioned it was installed and tested successfully from the Primary Prompt. Could it be a path definition issue or something like that? This is the current directory where the module is installed:
usr/local/lib/python2.7/dist-packages/colorama-0.3.7-py2.7.egg
Does this path needs to be defined somewhere? Sorry I'm new on Python.
Any help would be appreciated.
Thank you.

Hopefully you have worked out the answer by now but have you tried specifying Fore?
When I use the colorama module I start with this:
import os, colorama
from colorama import Fore,Style,Back #specifying all 3 types
os.system("mode con: cols=120 lines=30") #sometimes colorama doesnt work
#when double clicking a python app so I use this to "prompt" command line
#and then it works fine colorama.init() should work too
Example code:
import os, colorama
from colorama import Fore,Style,Back
os.system("mode con: cols=120 lines=30")
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
If this doesnt work for you let me know :)

Related

Why can't I import WD_ALIGN_PARAGRAPH from docx.enum.text?

I transferred some code from IDLE 3.5 (64 bits) to pycharm (Python 2.7). Most of the code is still working, for example I can import WD_LINE_SPACING from docx.enum.text, but for some reason I can't import WD_ALIGN_PARAGRAPH.
At first, nearly non of the imports worked, but after I did
pip install python-docx
instead of
pip install docx
most of the imports worked except for WD_ALIGN_PARAGRAPH.
# works
from __future__ import print_function
import xlrd
import xlwt
import os
import subprocess
from calendar import monthrange
import datetime
from docx import Document
from datetime import datetime
from datetime import date
from docx.enum.text import WD_LINE_SPACING
from docx.shared import Pt
# does not work
from docx.enum.text import WD_ALIGN_PARAGRAPH
I don't get any error messages but Pycharm marks the line as error:
"Cannot find reference 'WD_ALIGN_PARAGRAPH' in 'text.py'".
You can use this instead:
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
and then substitute WD_PARAGRAPH_ALIGNMENT wherever WD_ALIGN_PARAGRAPH would have appeared before.
The reason this is happening is that the actual enum object is named WD_PARAGRAPH_ALIGNMENT, and a decorator is applied that also allows it to be referenced as WD_ALIGN_PARAGRAPH (which is a little shorter, and possibly clearer). I expect the syntax checker in PyCharm is operating on direct module attributes and doesn't pick up the alias, which is resolved by the Python parser/compiler.
Interestingly, I expect your code would work fine either way. But to get rid of the annoying message you can use the base name.
If someone uses pylint it can be easily suppressed with # pylint: disable=E0611 added at the end of the import line.

Shebang command to call script from existing script - Python

I am running a python script on my raspberry pi, at the end of which I want to call a second python script in the same directory. I call it using the os.system() command as shown in the code snippet below but get import errors. I understand this is because the system interprets the script name as a shell command and needs to be told to run it using python, using the shebang line at the beginning of my second script.
#!/usr/bin/env python
However doing so does not solve the errors
Here is the ending snippet from the first script:
# Time to Predict E
end3 = time.time()
prediction_time = end3-start3
print ("\nPrediction time: ", prediction_time, "seconds")
i = i+1
print (i)
script = '/home/pi/piNN/exampleScript.py'
os.system('"' + script + '"')
and here is the beginning of my second script:
'#!usr/bin/env python'
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#from picamera import PiCamera
import argparse
import sys
import time
import numpy as np
import tensorflow as tf
import PIL.Image as Image
Any help is greatly appreciated :)
Since you have not posted the actual errors that you get when you run your code, this is my best guess. First, ensure that exampleScript.py is executable:
chmod +x /home/pi/piNN/exampleScript.py
Second, add a missing leading slash to the shebang in exampleScript.py, i.e. change
'#!usr/bin/env python'
to
'#!/usr/bin/env python'
The setup that you have here is not ideal.
Consider simply importing your other script (make sure they are in the same directory). Importing it will result in the execution of all executable python code inside the script that is not wrapped in if __name__ == "__main__":. While on the topic, should you need to safeguard some code from being executed, place it in there.
I have 2 python file a.py and b.py and I set execute permission for b.py with.
chmod a+x b.py
Below is my sample:
a.py
#!/usr/bin/python
print 'Script a'
import os
script = './b.py'
os.system('"' + script + '"')
b.py
#!/usr/bin/python
print 'Script b'
Execute "python a.py", the result is:
Script a
Script b

Sniff error in Scapy

I am trying to use scapy for one of my project. But, it gives the following error, When I test it.
NameError: name 'sniff' is not defined
import sys
from scapy import *
devices = set()
def PacketHandler(pkt):
if pkt.haslayer(Dot11) :
dot11_layer = pkt.getlayer(Dot11)
if dot11_layer.addr2 and ( dot11_layer.addr2 not in devices ):
devices.add(dot11_layer.addr2)
print dot11_layer.addr2
sniff(iface = sys.argv[1], count = int(sys.argv[2]), prn = PacketHandler)
if I change module name to scapy.all, it says there is no module.
Python version: 2.7
Scapy version: 2.3.3
I have just installed with pip install scapy.Any helps would be appreciated.
You must import Scapy as from scapy.all import *, and you must not name your script scapy.py (or any other script in the current directory or your PYTHONPATH)!

ImportError: No module named stanford_segmenter

The StanfordSegmenter does not have an interface in nltk, different from the case of StanfordPOStagger or StanfordNER. So to use it, basically I have to create an interface manually for StanfordSegmenter, namely stanford_segmenter.py under ../nltk/tokenize/. I follow the instructions here http://textminingonline.com/tag/chinese-word-segmenter
However, when I tried to run this from nltk.tokenize.stanford_segmenter import stanford_segmenter, I got an error
msg Traceback (most recent call last):
File "C:\Users\qubo\Desktop\stanfordparserexp.py", line 48, in <module>
from nltk.tokenize.stanford_segmenter import stanford_segmenter
ImportError: No module named stanford_segmenter
[Finished in 0.6s]
The instructions mentioned to reinstall nltk after creating the stanford_segmenter.py. I don't quite get the point but so I did. However, the process can hardly be called 'reinstall', but rather a detaching and reconnecting nltk to python libs.
I'm using Windows 64 and Python 2.7.11. NLTK and all relevant pkgs are updated to the latest version. Wonder if you guys can shed some light on this. Thank you all so much.
I was able to import the module by running the following code:
import imp
yourmodule = imp.load_source("module_name.py", "/path/to/module_name.py")
yourclass = yourmodule.TheClass()
yourclass is an instance of the class and TheClass is the name of the class you want to create the obj in. This is similar to the use of:
from pkg_name.module_name import TheClass
So in the case of StanfordSegmenter, the complete lines of code is as follows:
# -*- coding: utf-8 -*-
import imp
import os
ini_path = 'D:/jars/stanford-segmenter-2015-04-20/'
os.environ['STANFORD_SEGMENTER'] = ini_path + 'stanford-segmenter-3.5.2.jar'
stanford_segmenter = imp.load_source("stanford_segmenter", "C:/Users/qubo/Miniconda2/pkgs/nltk-3.1-py27_0/Lib/site-packages/nltk/tokenize/stanford_segmenter.py")
seg = stanford_segmenter.StanfordSegmenter(path_to_model='D:/jars/stanford-segmenter-2015-04-20/data/pku.gz', path_to_jar='D:/jars/stanford-segmenter-2015-04-20/stanford-segmenter-3.5.2.jar', path_to_dict='D:/jars/stanford-segmenter-2015-04-20/data/dict-chris6.ser.gz', path_to_sihan_corpora_dict='D:/jars/stanford-segmenter-2015-04-20/data')
sent = '我有一只小毛驴我从来也不骑。'
text = seg.segment(sent.decode('utf-8'))

Installing NodeboxOpenGL on windows

Hello I am trying to install and make use of NodeboxOpenGL, the python library so I can create my own graphs with nodes and edges. But I am running into some trouble,
starting off at NodeBox OpenGL site. I downloaded NodeBox for OpenGL and then pyglet, I then did easy_install nodebox-opengl.
Note I did not do pip install
I installed pyglet from pyglet. So now I am thinking its all ready to go. I did a quick check of my c:\python27\Lib\site-packages\ location just be sure the nodebox folder was there, all seems good.
I tried the sample program that's on the site
from nodebox.graphics import *
from nodebox.graphics.physics import Flock
flock = Flock(40, 0, 0, 500, 500)
flock.sight = 300
def draw(canvas):
background(1)
fill(0, 0.75)
flock.update(cohesion=0.15)
for boid in flock:
push()
translate(boid.x, boid.y)
scale(0.5 + 1.5 * boid.depth)
rotate(boid.heading)
arrow(0, 0, 15)
pop()
canvas.fps = 30
canvas.size = 600, 400
canvas.run(draw)
tried to run it, but i keep getting this error
Traceback (most recent call last):
File "E:\Workspace\ElasticNodes\graph1.py", line 5, in <module>
from nodebox.graphics import *
File "E:\Workspace\ElasticNodes\nodebox\graphics\__init__.py", line 1, in <module>
import bezier
File "E:\Workspace\ElasticNodes\nodebox\graphics\bezier.py", line 10, in <module>
from context import BezierPath, PathElement, PathError, Point, MOVETO, LINETO, CURVETO, CLOSE
File "E:\Workspace\ElasticNodes\nodebox\graphics\context.py", line 29, in <module>
import geometry
File "E:\Workspace\ElasticNodes\nodebox\graphics\geometry.py", line 454, in <module>
from pyglet.gl import \
ImportError: cannot import name pointer
I tried modifying the python script i.e
In your script, add the location of NodeBox to sys.path, before importing it: >>> MODULE = '/users/tom/python/nodebox' >>> import sys; if MODULE not in sys.path: sys.path.append(MODULE) >>> import nodebox
But still the same error.
I am using Python2.7, running on windows. I am not sure what I am doing wrong. Has anyone got any experience with running this library on windows. What am I doing wrong
Maybe this helps you:
In geometry.py del "pointer" import. Replace pointer(data) to POINTER(data)
I also had another error, so maybe you need add import to "shaders.py": from ctypes import c_uint
I am having a similar problem with Linux. The Nodebox-opengl site ( http://www.cityinabottle.org/nodebox/ ) says that python 2.5 or 2.6 must be used, so it is possible that the problem is that you are using 2.7.
EDIT:
Ok, I installed pyglet first, with pip (and or apt-get, I did both) and I don't get a problem with pyglet. But I still do get other problems.