Python Import
I seem to be having a rather annoying import issue with python. I am programming a small game using pygame, I'm almost complete with it, but have become rather annoyed that my source code for it is rather ugly and unordered. I wanted to be able to remove certain segments of code, for example, enemy code, character code, ect. In different files, and just use python to access them. I figured out that from <blah> import * would be the best way, but since some of the code, image directories ect, is in the main program, the other modules complain about not being able to access the images, saying they don't exsist. I tried module.Img.character and still the same error persist. Any ideas on what I am doign wrong?
I'm not quite sure what you're asking (what is 'module.Img.character' supposed to be/do?), but it sounds like you might need to move the stuff that is needed by various non-main modules out of the main module - to avoid looping dependencies.
Also 'from <blah> import *' should be used with caution, it is normally better to import names explicitly, or else just do 'import <blah>', to avoid name clashes, etc.
Similar Messages
-
Python Import failures while installing unqlite
I'm trying to install unqlite-python but I'm getting following error.
File "ctypesgen/ctypesgen.py", line 38, in <module>
import ctypesgencore
File "/tmp/pip-build-5mqtbyod/unqlite/ctypesgen/ctypesgencore/__init__.py", line 60, in <module>
import descriptions
ImportError: No module named 'descriptions'
I've installed required dependancies, the 'descriptions' module happens to be the one in the exact same folder as __init__.py
I've had similar problem in my project earlier but I don't remember what fixed it.
I tried to install unqlite with pip on OS X 10.10 and Fedora 22, where it installed without any errors, the problem only persists for Arch Linux, so it seems it's more Arch related.. maybe?
I also tried if I can recreate the error in Arch Linux but import seems to work fine, Currently the problem seems to be with only this specific package.I tried installing unqlite on both Python 2 and Python 3
with
sudo pip2 install unqlite
and
sudo pip3 install unqlite
I get the above error for both Python versions, (2.7.10 and 3.4.3).. on Arch Linux only.
├── ctypesgen
│ ├── ctypesgencore
│ │ ├── ctypedescs.py
│ │ ├── descriptions.py
│ │ ├── expressions.py
│ │ ├── __init__.py
│ │ ├── libraryloader.py
│ │ ├── messages.py
│ │ ├── old libraryloader.py
│ │ ├── options.py
│ │ ├── parser
│ │ │ ├── cdeclarations.py
│ │ │ ├── cgrammar.py
│ │ │ ├── cparser.py
│ │ │ ├── ctypesparser.py
│ │ │ ├── datacollectingparser.py
│ │ │ ├── __init__.py
│ │ │ ├── lex.py
│ │ │ ├── lextab.py
│ │ │ ├── parsetab.py
│ │ │ ├── pplexer.py
│ │ │ ├── preprocessor.py
│ │ │ └── yacc.py
│ │ ├── printer
│ │ │ ├── defaultheader.py
│ │ │ ├── __init__.py
│ │ │ ├── preamble.py
│ │ │ ├── printer.py
│ │ │ └── test.py
│ │ └── processor
│ │ ├── dependencies.py
│ │ ├── __init__.py
│ │ ├── operations.py
│ │ └── pipeline.py
│ ├── ctypesgen.py
│ └── __init__.py
├── docs
│ ├── api.rst
│ ├── conf.py
│ ├── index.rst
│ ├── installation.rst
│ ├── Makefile
│ └── quickstart.rst
├── LICENSE
├── MANIFEST.in
├── README.md
├── setup.py
└── unqlite
├── core.py
├── __init__.py
├── src
│ ├── unqlite.c
│ └── unqlite.h
└── tests.py
I tried to get similar error by creating similar module structure but it worked fine..
I get the error when I try to build the module manually with
python setup.py build
as you can see, build throws error for every local module in unqlite directory.. i.e 'printer', 'parser','processor'.. followed by 'descriptions', 'options' etc.
Secondly, I maintain different virtualenviroments for my each project so installing with pip is fairly safe.
The system wide python modules are installed with pacman only.
Last edited by b2bwild (2015-06-01 05:54:32) -
Launching programs from python and ncurses
I've made a little menu launcher with python and ncurses. It works most of the time, but occationally it does nothing when I select a program to launch.
This is how it works:
1. A keyboard shortcut launches an xterm window that runs the program.
2. I select some program, which is launched via this command:
os.system("nohup " + "program_name" + "> /dev/null &")
3. ncurses cleans up and python calls "sys.exit()"
The whole idea with nohup is that the xterm window will close after I select an application, but the application will still start normally (this was a bit of a problem). This works most of the time, but sometimes nothing happens (it never works the first time I try launching a program after starting the computer, the other times are more random).
So, has anyone got an idea of what's going on or a better solution than the nohup hack?
The whole code for the menu launcher is below. It's quite hackish, but then again it was just meant for me. The file's called "curmenu.py", and I launch it with an xbindkeys shortcut that runs "xterm -e curmenu.py".
#!/usr/bin/env python
import os,sys
import curses
## Variables one might like to configure
programs = ["Sonata", "sonata", "Ncmpc", "xterm -e ncmpc", "Emacs", "emacs", "Firefox", "swiftfox",\
"Pidgin", "pidgin", "Screen", "xterm -e screen", "Thunar", "thunar", \
"Gimp", "gimp", "Vlc", "vlc", "Skype", "skype"]
highlight = 3
on_screen = 7
## Functions
# Gets a list of strings, figures out the middle one
# and highlights it. Draws strings on screen.
def drawStrings(strings):
length = len(strings)
middle = (length - 1)/2
for num in range(length):
addString(strings[num], middle, num, length)
stdscr.refresh()
def addString(string, middle, iter_step, iter_max):
if iter_step < iter_max:
string = string + "\n"
if iter_step == middle:
stdscr.addstr(iter_step + 1, 1, string, curses.A_REVERSE)
else:
stdscr.addstr(iter_step + 1, 1, string)
# Returns a list of strings to draw on screen. The
# strings chosen are centered around position.
def listStrings(strings, position, on_screen):
length = len(strings)
low = (on_screen - 1)/2
start = position - low
str = []
for num in range(start, start + on_screen):
str = str + [strings[num % length]]
return str
## Start doing stuff
names = programs[::2]
longest = max(map(lambda x: len(x), names))
# Start our screen
stdscr=curses.initscr()
# Enable noecho and keyboard input
curses.curs_set(0)
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
# Display strings
drawStrings(listStrings(names, highlight, on_screen))
# Wait for response
num_progs = len(names)
low = (on_screen - 1)/2
while 1:
c = stdscr.getch()
if c == ord("q") or c == 27: # 27 = "Escape"
break
elif c == curses.KEY_DOWN:
highlight = (highlight + 1)%num_progs
elif c == curses.KEY_UP:
highlight = (highlight - 1)%num_progs
elif c == curses.KEY_NPAGE:
highlight = (highlight + low)%num_progs
elif c == curses.KEY_PPAGE:
highlight = (highlight - low)%num_progs
elif c == 10: # actually "Enter", but hey
os.system("nohup " + programs[2*highlight + 1] + "> /dev/null &")
break
drawStrings(listStrings(names, highlight, on_screen))
# Close the program
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
sys.exit()Try:
http://docs.python.org/lib/module-subprocess.html
Should let you fork programs off into the background. -
[Solved] Help needed to interpret errors (python)
Have the following code (Haven't written it my self and don't know much about how it does what it's supposed to do.):
#!/usr/bin/python
import sys
import os
import re
import logging
import json
if sys.version_info < (3, 0):
from urllib2 import Request
from urllib2 import urlopen
from urlparse import urlparse
else:
from urllib.request import Request
from urllib.request import urlopen
from urllib.parse import urlparse
raw_input = input
useragent = 'Mozilla/5.0'
headers = {'User-Agent': useragent}
intro = """
Usage: drdown.py url
This script finds the stream URL from a dr.dk page so you can
download the tv program.
def fetch(url):
"""Download body from url"""
req = Request(url, headers=headers)
response = urlopen(req)
body = response.read()
response.close()
# convert to string - it is easier to convert here
if isinstance(body, bytes):
body = body.decode('utf8')
return body
class StreamExtractor:
def __init__(self, url):
self.url = url.lower()
self.urlp = urlparse(self.url)
def get_stream_data(self):
"""supply a URL to a video page on dr.dk and get back a streaming
url"""
if self.urlp.netloc not in ('dr.dk', 'www.dr.dk'):
raise Exception("Must be an URL from dr.dk")
self.html = fetch(self.url)
logging.info("Player fetched: " + self.url)
# Standalone show?
if self.urlp.path.startswith('/tv/se/'):
return self.get_stream_data_from_standalone()
# Bonanza?
elif self.urlp.path.startswith('/bonanza/'):
return self.get_stream_data_from_bonanza()
# Live tv?
elif self.urlp.path.startswith('/tv/live'):
return self.get_stream_data_from_live()
else:
return self.get_stream_data_from_series()
def get_stream_data_from_rurl(self, rurl):
"""Helper method to parse resource JSON document"""
body = fetch(rurl)
resource_data = json.loads(body)
qualities = resource_data.get('links')
# sort by quality
qualities = sorted(qualities, key=lambda x: x['bitrateKbps'],
reverse=True)
stream_data = qualities[0]
stream_url = stream_data.get('uri')
logging.info("Stream data fetched: " + stream_url)
playpath, filename = self.get_metadata_from_stream_url(stream_url)
stream_data = {'stream_url': stream_url,
'playpath': playpath,
'filename': filename,
'is_live': False}
return stream_data
def get_metadata_from_stream_url(self, stream_url):
"""Helper method to extacts playpath and filename suggestion from a
rtmp url"""
parsed = urlparse(stream_url)
playpath_s = parsed.path.split('/')[2:]
playpath = '/'.join(playpath_s)
# rerun to split the parameter
path = urlparse(parsed.path).path
filename = path.split('/')[-1]
return playpath, filename
def get_stream_data_from_standalone(self):
"""Extracts stream data from a normal single program page.
The data is hidden in a resource URL, that we need to download
and parse.
mu_regex = re.compile('resource: "([^"]+)"')
m = mu_regex.search(self.html)
if m and m.groups():
resource_meta_url = m.groups()[0]
return self.get_stream_data_from_rurl(resource_meta_url)
def get_stream_data_from_bonanza(self):
"""Finds stream URL from bonanza section. Just pick up the first RTMP
url.
stream_regex = re.compile('rtmp://.*?\.mp4')
m = stream_regex.search(self.html)
if m and m.group():
stream_url = m.group()
else:
raise Exception("Could not find Bonanza stream URL")
playpath, filename = self.get_metadata_from_stream_url(stream_url)
stream_data = {'stream_url': stream_url,
'playpath': playpath,
'filename': filename,
'is_live': False}
return stream_data
def get_stream_data_from_live(self):
stream_url = 'rtmp://livetv.gss.dr.dk/live'
quality = '3'
playpaths = {'dr1': 'livedr01astream',
'dr2': 'livedr02astream',
'dr-ramasjang': 'livedr05astream',
'dr-k': 'livedr04astream',
'dr-update-2': 'livedr03astream',
'dr3': 'livedr06astream'}
urlend = self.urlp.path.split('/')[-1]
playpath = playpaths.get(urlend)
filename = 'live.mp4'
if playpath:
playpath += quality
filename = urlend + '.mp4'
stream_data = {'stream_url': stream_url,
'playpath': playpath,
'filename': filename,
'is_live': True}
return stream_data
def get_stream_data_from_series(self):
"""dr.dk has a special player for multi episode series. This is the
fall back parser, as there seems to be no pattern in the URL."""
slug_regex = re.compile('seriesSlug=([^"]+)"')
m = slug_regex.search(self.html)
if m and m.groups():
slug_id = m.groups()[0]
else:
raise Exception("Could not find program slug")
logging.info("found slug: " + slug_id)
program_meta_url = 'http://www.dr.dk/nu/api/programseries/%s/videos'\
% slug_id
body = fetch(program_meta_url)
program_data = json.loads(body)
if not program_data:
raise Exception("Could not find data about the program series")
fragment = self.urlp.fragment
if fragment.startswith('/'):
fragment = fragment[1:]
fragment = fragment.split('/')
video_id = fragment[0]
logging.info("Video ID: " + video_id)
video_data = None
if video_id:
for item in program_data:
if item['id'] == int(video_id):
video_data = item
if not video_data:
video_data = program_data[0]
resource_meta_url = video_data.get('videoResourceUrl')
return self.get_stream_data_from_rurl(resource_meta_url)
def generate_cmd(self):
"""Build command line to download stream with the rtmpdump tool"""
sdata = self.get_stream_data()
if not sdata:
return "Not found"
filename = sdata['filename']
custom_filename = raw_input("Type another filename or press <enter> to keep default [%s]: " % filename)
if custom_filename:
filename = custom_filename
cmd_live = 'rtmpdump --live --rtmp="%s" --playpath="%s" -o %s'
cmd_rec = 'rtmpdump -e --rtmp="%s" --playpath="%s" -o %s'
if sdata['is_live'] is True:
cmd = cmd_live % (sdata['stream_url'], sdata['playpath'], filename)
else:
cmd = cmd_rec % (sdata['stream_url'], sdata['playpath'], filename)
return cmd
def main():
if len(sys.argv) > 1:
url = sys.argv[1]
extractor = StreamExtractor(url)
cmd = extractor.generate_cmd()
os.system(cmd)
else:
print(intro)
if __name__ == "__main__":
main()
When I run the script with an appropriate URL as parameter, I get this:
Traceback (most recent call last):
File "./drdown.py", line 243, in <module>
main()
File "./drdown.py", line 235, in main
cmd = extractor.generate_cmd()
File "./drdown.py", line 211, in generate_cmd
sdata = self.get_stream_data()
File "./drdown.py", line 65, in get_stream_data
return self.get_stream_data_from_standalone()
File "./drdown.py", line 123, in get_stream_data_from_standalone
return self.get_stream_data_from_rurl(resource_meta_url)
File "./drdown.py", line 87, in get_stream_data_from_rurl
reverse=True)
TypeError: 'NoneType' object is not iterable
I should note that I didn't expect it to work out of the box, but so far I've been unable even to figure out what the problem is, no less solve it.
I've tried my best to go through the code, looking for typos and such, but I haven't had any luck and much of what happens I don't really understand.
So please, if you can, I'd very much appreciate a little help.
Best regards.
NB:
Some might conclude that this script does something illegal. In actuality that is not so, just make that clear. Also, testing from outside Denmark, will probably not be possible.
Last edited by zacariaz (2013-11-08 18:00:33)Trilby wrote:
zacariaz wrote:Have the following code (Haven't written it my self and don't know much about how it does what it's supposed to do.)
You know a lot more than we do: like where you then found this code, and what it is supposed to do.
My only first thought without looking through random code that allegedly serves some unknown purpose and comes from some unknown source is that the shebang is ambiguous: it may be a python 2 script while /usr/bin/python is now python 3.
I've pretty much concluded that python 3.3 is the right choice, sp that should not be a problem, as for what it does, it uses "rtmpdump" to record or "rip" video from a danish site "dr.dk", which is a public service television network.
I have it from reliable sources that this actually works, or at least did at some point, on Windows machines, but of course i'm on linux, and that complicated matters.
All in all, as I understand it, what the script really does, is retrieving the relevant rtmp link. The rest is up to "rmtpdump" which I should be able to manage.
In any case, I'm not really that concerned with learning what the script does at this point, but rather what the error mean.
The only actual error description I see is: "TypeError: 'NoneType' object is not iterable" and I haven't a clue what that implies. I've read through the script, but haven't been able to find any obvious flaws.. -
[Solved] Python CGI - how to "include" like in PHP
Hi.
When I code PHP I like to use this template system. A short instance would consist of 2 files: "index.php" and "template.php".
template.php:
<?php
echo "<h1>$header</h1>";
echo "<p>$text</p>";
?>
index.php:
<?php
$header = "this is a header";
$text = "this is a text";
include "template.php";
?>
So I can use one template for lots of pages - same layout but different vars.
I cannot find how to do this in Python CGI.
page.cgi:
#!/usr/bin/python
import os, cgi
x = "This is the page text."
eval(open('template.cgi').read())
template.cgi
print("Content-type: text/html\n")
print(x)
This gives me error 500. I am not surprised, this mail.python.org page says:
> I can't figure out how one would approach this in Python (i'm using
> mod_python). There's no equivalent to the "include" function from
> PHP.
Correct, the concept doesn't exist because you are working
with vanilla CGI rather than server scripting.
But maybe there is a way to make something similar?
Last edited by Mr. Alex (2012-06-05 17:52:42)Template (index.html.tpl)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Main Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
h1 {{
margin: auto;
</style>
</head>
<body>
<h1>Admin</h1>
<ul>
<li><a href="{}">Monthly Report</a></li>
<li><a href="{}">Inventory Zip Files</a></li>
<li><a href="{}">Order Reports</a> -- Last 7 days</li>
<li><a href="{}">Notes/TODO/Information</a></li>
<li><a href="{}">EDI Orders</a></li>
</ul>
</body>
</html>
index.py :
#!/usr/bin/env python2
def main():
template = "index.html.tpl"
pages = ("monthly", "zips", "reports", "vimwiki", "edi.py")
sitename = "/"
pages = ["{}{}".format(sitename, pages) for i in pages]
tpl = "".join(open(template,'r').readlines())
print 'Content-type: text/html\n\n' + tpl.format(*pages)
if __name__ == '__main__':
main()
Maybe not the best way...but it works for me Notice the double {{ }} in the template where you want literal brackets, not placeholders.
Scott -
Hi guys, I'm trying to make a socket connection between Flash and Python but, I'm getting a Security Error with policy file.
Tried this:
Python:
import socket
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(('', 2020))
serverSocket.listen(1)
conn, addr = serverSocket.accept()
while True:
data = conn.recv(1024)
if not data: break
if "<policy-file-request/>\0" in data:
conn.send("""<?xml version="1.0"?><cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>""")
conn.send(data)
Flash:
Security.loadPolicyFile("xmlsocket://127.0.0.1:2020");
It isn't working, someone can help me?!To add to Mike's answer, the only caveat is that the server needs an appropriate clientaccesspolicy.xml file at the root level (http://yourserver/clientaccesspolicy.xml), or a completely open crossdomain.xml file, for the editor and built apps to be able to communicate with it. There's a help topic which explains this in the context of LV web services, but it's true for Web UI Builder to be able to communicate with arbitrary web servers also.
Since it sounds like you control all the web servers in question, it shouldn't be too difficult to get this file in place, though. -
Problem with package python-pyparallel
I'm trying to install python-pyparallel. The problem is that after I install it I do in python:
">>> import parallel"
And the module is not found.
So I checked the package and, I'm not an expert but it doesn't have any binary or python file or anything that points to any kind of file, directory or url.
Can you please check. Thanks._Mike_ wrote:
Can you pls explain me how can I fix this with simple instructions?
Are you able to import parallel module in python now?
I tried downloading pyparallel from it's official homepage, unzipped and did "python setup.py install" and I got a lot of errors.
wait couples of hours(minutes) and do pacman -Syu.
i fixed the package -
Python - Screenkey and Key-mon won't start (SOLVED)
You can see from the information supplied below that screenkey is set to
use python2 while key-mon is not. However, the errors are pretty similar.
What could be done?
vaio@nando, Wed Oct 27 06:56:53
~ $
bash >>> screenkey
Traceback (most recent call last):
File "/usr/bin/screenkey", line 23, in <module>
from Screenkey import APP_NAME, APP_DESC, VERSION
ImportError: No module named Screenkey
=========================================================
vaio@nando, Wed Oct 27 07:00:50
~ $
bash >>> sed -n '1p' /usr/bin/screenkey
#!/usr/bin/python2
========================================================
vaio@nando, Wed Oct 27 06:56:53
~ $
bash >>> key-mon
Traceback (most recent call last):
File "/usr/bin/key-mon", line 2, in <module>
import keymon.key_mon as km
ImportError: No module named keymon.key_mon
========================================================
vaio@nando, Wed Oct 27 07:01:02
~ $
bash >>> sed -n '1,5p' /usr/bin/key-mon
#!/usr/bin/python
import keymon.key_mon as km
km.main()
EDIT: Solved by rebuilding the packages.
Last edited by FernandoBasso (2010-10-27 15:56:42)As seen on irc(tm):
User didn't rebuilt the package when python 2.6 was updated to 2.7
Python 2.7 does not look into /usr/lib/python2.6/
Fixed by rebuilding/reinstalling. -
Lemme preface this post by saying the following - I've taken my computer to the local IT office on RIT campus, asked a Computer Science professor specializing in Python, and posted my question on answers.yahoo.com (I don't know why I expected that to work...). I've also googled my problem multiple times and have not come up with anything newer than about 4 years ago. Also I'm positive this is an issue with my computer because I have copied and pasted python 2.7, as well as EVERY corresponding framework to my iMac from my laptop which is running it perfectly.
Okay, so the problem. I tried to install Python 2.7 about two months ago on both my laptop and iMac. Both are running up-to-date Mac OS X
10.6, with 64-bit processors and around 2.4GHz speed and 2G of RAM. My laptop installed python 2.7 and ran it perfectly, first time. My desktop... not so much.
How to recreate the issue on iMac - try to open IDLE, or in terminal, type the following:
python
import turtle
turtle.up()
This is what's displayed in terminal:
COMPUTERNAME:~ USER$ python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import turtle
>>> turtle.up()
CGColor with 1 components
Abort trap
COMPUTERNAME:~ USER$
It also pops up a Problem Report for Python:
Python quit unexpectedly.
Click Reopen to open the application again. This report will be sent
to Apple automatically.
Problem Details and System Configuration
Process: Python [33535]
Path: /Library/Frameworks/Python.framework/Versions/2.7/
Resources/Python.app/Contents/MacOS/Python
Identifier: org.python.python
Version: 2.7.2 (2.7.2)
Code Type: X86-64 (Native)
Parent Process: bash [33532]
Date/Time: 2011-11-10 17:31:58.424 -0500
OS Version: Mac OS X 10.6.8 (10K549)
Report Version: 6
Interval Since Last Report: 1141508 sec
Crashes Since Last Report: 2
Per-App Interval Since Last Report: 2 sec
Per-App Crashes Since Last Report: 2
Anonymous UUID: C667A2E4-5530-4A3E-B6E3-
B38E970458E5
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Application Specific Information:
abort() called
Thread 0 Crashed: Dispatch queue: com.apple.main-thread
0 libSystem.B.dylib 0x00007fff89bd40b6 __kill + 10
1 libSystem.B.dylib 0x00007fff89c749f6 abort + 83
2 Tcl 0x000000010067f9ef Tcl_Panic + 0
3 Tcl 0x000000010067fa91 Tcl_Panic + 162
4 Tk 0x00000001010ac5a7 TkpGetColor +
383
5 Tk 0x00000001010b9a2a TkpMenuInit +
156
6 Tk 0x000000010103c36c TkMenuInit + 88
7 Tk 0x00000001010bc68b -
[TKApplication(TKMenus) _setupMenus] + 53
8 Tk 0x00000001010b6d27 -
[TKApplication(TKInit) _setup:] + 56
9 Tk 0x00000001010b7260 TkpInit + 545
10 Tk 0x000000010102da26 Initialize +
1678
11 _tkinter.so 0x00000001005fccfb Tcl_AppInit + 75
12 _tkinter.so 0x00000001005fa153 Tkinter_Create +
915
13 org.python.python 0x00000001000c102d
PyEval_EvalFrameEx + 22397
14 org.python.python 0x00000001000c2d29
PyEval_EvalCodeEx + 2137
15 org.python.python 0x000000010003da80 function_call +
176
16 org.python.python 0x000000010000c5e2 PyObject_Call +
98
17 org.python.python 0x000000010001ebcb
instancemethod_call + 363
18 org.python.python 0x000000010000c5e2 PyObject_Call +
98
19 org.python.python 0x00000001000be5f3
PyEval_EvalFrameEx + 11587
20 org.python.python 0x00000001000c2d29
PyEval_EvalCodeEx + 2137
21 org.python.python 0x000000010003da80 function_call +
176
22 org.python.python 0x000000010000c5e2 PyObject_Call +
98
23 org.python.python 0x000000010001ebcb
instancemethod_call + 363
24 org.python.python 0x000000010000c5e2 PyObject_Call +
98
25 org.python.python 0x00000001000ba5f7
PyEval_CallObjectWithKeywords + 87
26 org.python.python 0x0000000100021e5e PyInstance_New +
126
27 org.python.python 0x000000010000c5e2 PyObject_Call +
98
28 org.python.python 0x00000001000be5f3
PyEval_EvalFrameEx + 11587
29 org.python.python 0x00000001000c2d29
PyEval_EvalCodeEx + 2137
30 org.python.python 0x000000010003da80 function_call +
176
31 org.python.python 0x000000010000c5e2 PyObject_Call +
98
32 org.python.python 0x000000010001ebcb
instancemethod_call + 363
33 org.python.python 0x000000010000c5e2 PyObject_Call +
98
34 org.python.python 0x0000000100077a68 slot_tp_init +
88
35 org.python.python 0x0000000100074e65 type_call + 245
36 org.python.python 0x000000010000c5e2 PyObject_Call +
98
37 org.python.python 0x00000001000be5f3
PyEval_EvalFrameEx + 11587
38 org.python.python 0x00000001000c1ebe
PyEval_EvalFrameEx + 26126
39 org.python.python 0x00000001000c2d29
PyEval_EvalCodeEx + 2137
40 org.python.python 0x000000010003da80 function_call +
176
41 org.python.python 0x000000010000c5e2 PyObject_Call +
98
42 org.python.python 0x000000010001ebcb
instancemethod_call + 363
43 org.python.python 0x000000010000c5e2 PyObject_Call +
98
44 org.python.python 0x0000000100077a68 slot_tp_init +
88
45 org.python.python 0x0000000100074e65 type_call + 245
46 org.python.python 0x000000010000c5e2 PyObject_Call +
98
47 org.python.python 0x00000001000be5f3
PyEval_EvalFrameEx + 11587
48 org.python.python 0x00000001000c1ebe
PyEval_EvalFrameEx + 26126
49 org.python.python 0x00000001000c1ebe
PyEval_EvalFrameEx + 26126
50 org.python.python 0x00000001000c2d29
PyEval_EvalCodeEx + 2137
51 org.python.python 0x00000001000c2e46 PyEval_EvalCode
+ 54
52 org.python.python 0x00000001000e769c
PyRun_InteractiveOneFlags + 380
53 org.python.python 0x00000001000e78fe
PyRun_InteractiveLoopFlags + 78
54 org.python.python 0x00000001000e80e1
PyRun_AnyFileExFlags + 161
55 org.python.python 0x00000001000fe77c Py_Main + 2940
56 org.python.python 0x0000000100000f14 0x100000000 +
3860
Thread 1: Dispatch queue: com.apple.libdispatch-manager
0 libSystem.B.dylib 0x00007fff89b9ec0a kevent + 10
1 libSystem.B.dylib 0x00007fff89ba0add
_dispatch_mgr_invoke + 154
2 libSystem.B.dylib 0x00007fff89ba07b4
_dispatch_queue_invoke + 185
3 libSystem.B.dylib 0x00007fff89ba02de
_dispatch_worker_thread2 + 252
4 libSystem.B.dylib 0x00007fff89b9fc08
_pthread_wqthread + 353
5 libSystem.B.dylib 0x00007fff89b9faa5 start_wqthread +
13
Thread 2:
0 libSystem.B.dylib 0x00007fff89b9fa2a
__workq_kernreturn + 10
1 libSystem.B.dylib 0x00007fff89b9fe3c
_pthread_wqthread + 917
2 libSystem.B.dylib 0x00007fff89b9faa5 start_wqthread +
13
Thread 0 crashed with X86 Thread State (64-bit):
rax: 0x0000000000000000 rbx: 0x00007fff7116b2f8 rcx:
0x00007fff5fbfc0e8 rdx: 0x0000000000000000
rdi: 0x00000000000082ff rsi: 0x0000000000000006 rbp:
0x00007fff5fbfc100 rsp: 0x00007fff5fbfc0e8
r8: 0x00007fff7116ea60 r9: 0x0000000000000000 r10:
0x00007fff89bd00fa r11: 0x0000000000000206
r12: 0x00000001006ecb20 r13: 0x0000000000000001 r14:
0x00000001010e1f77 r15: 0x0000000000000000
rip: 0x00007fff89bd40b6 rfl: 0x0000000000000206 cr2:
0x00000001135b54f3
Model: iMac7,1, BootROM IM71.007A.B03, 2 processors, Intel Core 2 Duo,
2.4 GHz, 4 GB, SMC 1.20f4
Graphics: ATI Radeon HD 2600 Pro, ATI,RadeonHD2600, PCIe, 256 MB
Memory Module: global_name
AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0x88),
Broadcom BCM43xx 1.0 (5.10.131.42.4)
Bluetooth: Version 2.4.5f3, 2 service, 19 devices, 1 incoming serial
ports
Network Service: Built-in Ethernet, Ethernet, en0
Network Service: AirPort, AirPort, en1
Serial ATA Device: WDC WD3200AAJS-40RYA0, 298.09 GB
Parallel ATA Device: OPTIARC DVD RW AD-5630A, 406.7 MB
USB Device: Built-in iSight, 0x05ac (Apple Inc.), 0x8502,
0xfd400000 / 2
USB Device: Bluetooth USB Host Controller, 0x05ac (Apple Inc.),
0x8206, 0x1a100000 / 2
USB Device: Razer Naga, 0x1532, 0x0015, 0x1d100000 / 2
USB Device: IR Receiver, 0x05ac (Apple Inc.), 0x8242, 0x5d100000 / 2
I have tried copying every framework possible from the laptop to the iMac, done several reinstalls, and pretty much everything else I and the IT people on campus could think of to no avail. I've called Apple and even suggested paying for help to be told that there's nothing they can do to assist because it's not their software... I pointed out that it comes installed with every mac, and got no support STILL. I asked if he could tell me what my error report meant. His response of course was to try and post it on the development forums... I asked him where to go for help with this issue. He said his SUPERVISOR linked me to devloper.apple.com (not a hint of python there, btw) and python.org (...source of the problem?). I asked to talk to his supervisor and he told me I couldn't, he's on the phone... Yet he just gave him links for me... Suspicious.
I put this to you guys - help!Go to Options > General, and set your home page to "about:newtab" to go to the new tab page on startup.
-
Missing python libraries such as rsvg
Hello, I'm new to Arch Linux and Linux in general. I've just manually installed tpfand and tpfan-admin from https://launchpad.net/tp-fan which are fan controllers for Thinkpads. I had some trouble running tpfan-admin, because it was looking for a missing python import for rsvg.
So I commented everything that had to do with (r)svg in tpfan-admin/fan.py and was finally able to run tpfan-admin, just without the svg graphics for the fan. I ran it as unprivileged and pressed the Unlock button, expecting a popup asking for the root password. It crashed with the following output:
Traceback (most recent call last):
File "/usr/bin/tpfan-admin", line 24, in <module>
tpfanadmin.globals.temperature_dialog.run()
File "/usr/lib/python2.5/site-packages/tpfanadmin/temperaturedialog.py", line 297, in run
os.execvp(build.run_as_root_cmd, build.run_as_root_args)
File "/usr/lib/python2.5/os.py", line 353, in execvp
_execvpe(file, args)
File "/usr/lib/python2.5/os.py", line 389, in _execvpe
func(fullname, *argrest)
OSError: [Errno 2] No such file or directory
Running tpfan-admin as root works fine, but I'm worried that something messy is going on. Is there a clean way to install these Thinkpad fan control programs through pacman? Also, where can I get other python modules such as rsvg?
Thanks.There's a fan controller for the T60, but I doubt it would work on my R40. Thanks for the AUR tip though, I found dtach there as well
I found a fancontrol script under /usr/bin/ which relied on pwmconfig. pwmconfig bugs out on me saying something about fan divisors, but it has the nice side-effect of leaving my fans at 100%, which was exactly what I needed. Except that putting it in my rc.local script or running it as a daemon in rc.conf stops the fans after a few seconds rather than leaving them on. Am I doing something wrong? For now I'm forced to run pwmconfig manually on login. I really intend the laptop to be a personal server as well as for folding 24/7 so I'd prefer being able to start the fans without having to login. -
Memory leak (in Conky/python/curl?)
I'm showing ~35% mem usage on 4GB RAM with only one Firefox tab and two urxvt windows open. I'm getting conflicting information.
It looks like conky and firefox have both grabbed about half a gig together--even when I kill both and restart.
# archey says RAM: 1120 MB / 3020 MB
$ conky | dzen says 36%
# top (by mem) puts firefox at 5%, X at 1.4% and conky at .1%
# ps_mem:
[...snip]860.0 KiB + 298.5 KiB = 1.1 MiB polkitd
952.0 KiB + 208.5 KiB = 1.1 MiB gvfs-fuse-daemon
840.0 KiB + 360.0 KiB = 1.2 MiB dbus-daemon (2)
920.0 KiB + 329.0 KiB = 1.2 MiB gconfd-2
980.0 KiB + 303.0 KiB = 1.3 MiB gvfs-gdu-volume-monitor
1.3 MiB + 432.5 KiB = 1.7 MiB conky
1.2 MiB + 596.0 KiB = 1.8 MiB udisks-daemon (2)
1.3 MiB + 516.5 KiB = 1.8 MiB syslog-ng (2)
1.9 MiB + 222.5 KiB = 2.1 MiB vim
2.0 MiB + 308.5 KiB = 2.3 MiB cupsd
2.1 MiB + 1.0 MiB = 3.0 MiB bash (3)
3.1 MiB + 368.5 KiB = 3.5 MiB console-kit-daemon
5.1 MiB + 398.5 KiB = 5.5 MiB urxvt
6.8 MiB + 784.5 KiB = 7.6 MiB wicd-monitor
8.0 MiB + 473.0 KiB = 8.5 MiB wicd
6.7 MiB + 2.9 MiB = 9.6 MiB sakura
10.0 MiB + 1.0 MiB = 11.0 MiB slim
40.4 MiB + 746.0 KiB = 41.1 MiB Xorg
143.6 MiB + 3.5 MiB = 147.1 MiB firefox-bin
# memstat is a bit more revealing.
[root@thimkingpad nathan]# memstat | grep 25346
[b] 164544k: PID 25346 (/usr/bin/conky)[/b]
6568k( 340k): /usr/lib/libssl.so.1.0.0 1409 2075 25346 1409 2075 25346...
2208k( 152k): /usr/lib/libssh2.so.1 25346
10280k( 20k): /usr/lib/libXfixes.so.3.1.0 2344 4402 6957 25346 26764 2...
6152k( 8k): /usr/lib/libXdamage.so 4402 25346 26764 4402 25346 26764...
18464k( 32k): /usr/lib/libXrandr.so 1591 2344 4402 6957 6958 25346 253...
18524k( 56k): /usr/lib/libXi.so.6.1.0 1591 2344 4402 6957 6958 25346 2...
18488k( 20k): /usr/lib/libXtst.so.6 1591 2344 4402 6957 6958 25346 253...
15104k( 600k): /usr/lib/libfreetype.so.6.7.1 1831 1833 4402 6957 25346 ...
12536k( 200k): /usr/lib/libfontconfig.so.1.4.4 1831 4402 6957 25346 253...
16392k( 8k): /usr/lib/libswmhack.so.0 1591 4402 6957 6958 25346 25347...
7568k( 1316k): /usr/lib/libxml2.so.2.7.8 4402 25346 26764 4402 25346 26...
8272k( 80k): /usr/lib/libXft.so.2 1831 6957 25346 25347 1831 6957 253...
2396k( 340k): /usr/lib/libImlib2.so.1 25346
2432k( 372k): /usr/lib/libcurl.so.4 25346
2076k( 28k): /usr/lib/libiw.so 25346
356k( 348k): /usr/bin/conky 25346
10668k( 348k): /lib/libncursesw.so.5.9 1591 5213 6958 25346 26764 1591 ...
14424k( 60k): /lib/libbz2.so.1 1831 1833 4402 6957 25346 25347 26764 1...
But here conky isn't calling on that much by itself. Conky updates every 2 seconds and my config is:
${execpi 300 ~/Scripts/mail_counter.py} email(s) | ${addr wlan0} | BATT:${battery_short} | RAM:$memperc% | CPU: ${cpu cpu1}% ${cpu cpu2}% | FREE root ${fs_free /} home ${fs_free /home}
mail_counter.py is from the wiki IIRC. I didn't see python eating that much in memstat. There's that 2MB of curl but that's about it.
Lastly gmemusage portrays Firefox at ~300MB, Conky at 164MB, console-kit at 87MB, polkitd at 82MB, and udisks at 83MB.
Where's my RAM going? I had forgotten to plug my battery in and had to boot up just 15 hours ago X(
EDIT: Just rebooted, got to POST and GRUB and then got a black screen and bunch of beeping after selecting the regular kernel, which IIRC means RAM hardware issue. Able to boot into the fallback kernel fine, and into the regular one again after that. going to do a memtest.
Last edited by nathan28 (2011-09-22 15:54:25)That's the whole config, piped into dzen2. Only script running is the one in that conky config:
#! /usr/bin/python
import os
username=[foo]
password=[foo]
com="wget -q -O - https://"+username+":"+password+"@mail.google.com/mail/feed/atom --no-check-certificate"
temp=os.popen(com)
msg=temp.read()
index=msg.find("<fullcount>")
index2=msg.find("</fullcount>")
fc=int(msg[index+11:index2])
if fc==0:
print ("0 new")
else:
print (str(fc)+" new")
Daemons running should have been: alsa, crond, cupsd, dbus, iptables, netfs, ntpd, sensors, syslog-ng, thinkfan, wicd. -
Performing a mouse click using python
Is it possible?
I tried to use this script but it doesn't work:
#!/usr/bin/python
import Tkinter as tk
def change_color(event):
btn1.config(fg='red')
root = tk.Tk()
btn1 = tk.Button(root, text='Click me with the right mouse button ...')
btn1.pack()
btn1.bind('<Button-1>', change_color)
root.mainloop()
Thanks.Yes, I would like to do it without deps.
Here:
#!/usr/bin/env python
from Xlib.display import Display
from Xlib import X
from Xlib.protocol import event
import time
display = Display()
focus = display.get_input_focus().focus
keycode = 1
state = 0
keyevt = event.KeyPress(
detail=keycode,
time=X.CurrentTime,
root=display.screen().root,
window=focus,
child=X.NONE,
root_x=1,
root_y=1,
event_x=1,
event_y=1,
state=state,
same_screen=1)
state=1
keyevt2 = event.KeyPress(
detail=keycode,
time=X.CurrentTime,
root=display.screen().root,
window=focus,
child=X.NONE,
root_x=1,
root_y=1,
event_x=1,
event_y=1,
state=state,
same_screen=1)
focus.send_event(keyevt)
focus.send_event(keyevt2)
I think the problem is with the "state".
I checked it with xev, and it tells that the state on press is 0x10 (16 decimal?) and on release is 0x110 (272 decimal?).
I tried using these values too, and again, not working.
In addition, X.CurrentTime returns 0, so I tried using int(time.time()), and still, not working.
Any suggestions?
Thanks -
Python tool for keeping track of strings
I wrote this just now. It associates keys to strings; basically a centralized means of storing values.
#!/usr/bin/env python
from cPickle import load, dump
from sys import argv
from os.path import expanduser
strings_file = expanduser('~/lib/cfg-strings')
try:
with open(strings_file) as f:
strings = load(f)
except:
strings = {}
if len(argv) < 2:
print('''usage:
{0} dump
{0} get <key>
{0} del <key>
{0} set <key> <val>'''.format(argv[0]))
elif len(argv) == 2:
if argv[1] == 'dump':
for k in strings.keys(): print(k + ': ' + strings[k])
elif len(argv) == 3:
if argv[1] == 'get':
if argv[2] in strings.keys():
print(strings[argv[2]])
elif argv[1] == 'del':
if argv[2] in strings.keys():
del(strings[argv[2]])
elif len(argv) == 4:
if argv[1] == 'set':
strings[argv[2]] = argv[3]
with open(strings_file, 'w') as f:
dump(strings, f)
Replace '~/lib/cfg-strings' with your preferred destination for the pickle file.
As an example, I have this at the end of my .xinitrc:
exec $(cfg get wm)
so all I have to do is type "cfg set wm ..." to change my window manager. Note that on my system, the script is named 'cfg', so you'll want to change that depending on what you call it.
To be honest, though, I think everyone has written something like this at least once.
Last edited by Peasantoid (2010-01-18 01:29:14)Nice idea Peasantoid! I have wanted something similar for myself for a while now however wasn't exactly sure how best to do this. Here's my version. It is based on yours though as I prefer plain text for the settings file so I used JSON.
#!/usr/bin/python
import json
import os.path
import sys
SETTINGS_FILE = os.path.expanduser('~/configs/settings.json')
def dump(s):
print json.dumps(s, sort_keys = True, indent=2)
def get(s, key):
if s.has_key(key):
print s[key]
def set(s, key, val):
s[key] = val
save(s)
def delete(s, key):
if s.has_key(key):
del s[key]
save(s)
def save(s):
json.dump(s, open(SETTINGS_FILE, 'w'))
def usage():
str = [
"usage: %s dump (default)",
" %s get <key>",
" %s set <key> <val>",
" %s delete <key>"
for x in str:
print x % sys.argv[0]
def main():
try:
settings = json.load(open(SETTINGS_FILE))
except:
settings = {}
a = sys.argv
n = len(a)
if n == 1 or (n == 2 and a[1] == 'dump'):
dump(settings)
elif n == 3 and a[1] == 'get':
get(settings, a[2])
elif n == 3 and a[1] == 'delete':
delete(settings, a[2])
elif n == 4 and a[1] == 'set':
set(settings, a[2], a[3])
else:
usage()
if __name__ == "__main__":
main() -
[exaile] - contextual info OR using webkit in python
I have last Exaile version from the bzr and I'm trying to use Contextual Info pluging. When I activate the plugin I have next error message:
Could not enable plugin: No module named webkit.
As I know Exaile is written in Python I have created the small script in Python:
import webkit;
print "hi"
The script doesn't work:
demas@arch ~/temp $ python some.py
Traceback (most recent call last):
File "some.py", line 1, in <module>
import webkit
ImportError: No module named webkit
demas@arch ~ $ yaourt -Ss webkit
extra/libwebkit 1.1.10-2 [installed]
an opensource web content engine, derived from KHTML and KJS from KDE
community/pywebkitgtk 1.1.6-2 [installed]
Python bindings to the WebKit GTK+ port
aur/pywebkitgtk-svn 57-1 [145-1 installed] (51)
Python bindings to the WebKit GTK+ port
Whick package do I have to install to work with webkit in pyhon?http://bbs.archlinux.org/viewtopic.php?id=79011
-
[SOLVED] error when execute a python script in home partition
Friends,
After of install the Arch in my notebook (note: "/" and "/home" in separated partition) if I open a terminal/shell and try execute a python program/script in the /home partition I receive many erros and the program don't run:
[leandro@professionalit ~]$ alacarte
'import site' failed; use -v for traceback
Traceback (most recent call last):
File "/usr/bin/alacarte", line 22, in <module>
from Alacarte.MainWindow import MainWindow
ImportError: No module named Alacarte.MainWindow
[leandro@professionalit ~]$
[leandro@professionalit ~]$ dropbox start
'import site' failed; use -v for traceback
Traceback (most recent call last):
File "/usr/bin/dropbox", line 26, in <module>
import optparse
File "/usr/lib/python2.6/optparse.py", line 75, in <module>
import sys, os
File "os.py", line 2, in <module>
import socket
File "/usr/lib/python2.6/socket.py", line 92, in <module>
__all__.extend(os._get_exports_list(_socket))
AttributeError: 'module' object has no attribute '_get_exports_list'
But, if I go to another partition, for example, the folder opt in partition / (/opt) and try execute the program it run OK.
Any idea ?
Best regards,
Leandro.
Last edited by LeandroTiger (2010-05-21 23:02:29)[leandro@professionalit ~]$ pwd
/home/leandro
[leandro@professionalit ~]$ python
'import site' failed; use -v for traceback
Python 2.6.5 (r265:79063, Apr 1 2010, 05:22:20)
[GCC 4.4.3 20100316 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '', '/usr/lib/openoffice/basis-link/program/', '/usr/lib/python26.zip', '/usr/lib/python2.6/', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload']
>>> import site
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/site.py", line 62, in <module>
import os
File "os.py", line 2, in <module>
import socket
File "/usr/lib/python2.6/socket.py", line 92, in <module>
__all__.extend(os._get_exports_list(_socket))
AttributeError: 'module' object has no attribute '_get_exports_list'
>>> import Alacarte
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named Alacarte
>>>
Maybe you are looking for
-
hi sap experts, Is there any way that i can make a partial payment to a particular line item while running app. if so what should i configure in addition to the normal configuration. my payment method is check. Thanks in advance, Regards pavan kumar
-
Help Needed!! Working with SQL Databases
Hi All, I'm currently working on an application that interfaces with an SQL database, and I seem to have ran into a roadblock. I have a multicolumn list box on my front panel which is filled in with data extracted from the database. On selecting any
-
Condtion based xml for each row of the table t-sql
Hello , i have below data. create table #students id int identity(1,1) primary key, student_id int not null, [s_m_cml] xml insert into #students student_id, [s_m_xml] values 101, '<submarks><submark><subject>Arts</subject><marks>85</marks></submark><
-
We want profit center per Company Code, Plant and Material. In Trans. Code: 3KEH, we have Company Code and Valuation area which is not working in FI entry (plant). Can we add new condition for Derivation in 3KEH ? If yes, how? Is there any other way
-
FetchXML and Aggregate Functions (multiple datasets if necessary)
In fetch xml, How do I do conduct aggregate functions (most recent, sum, average) on retrieved columns, based on matches with another column. let's say column a has a value of "Timothy." How do I then find the total number of column b that also have