w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
python mercurial api: get incoming changes
First, You must pass to commands ui from repo object: repo.ui: commands.incoming(repo.ui, repo) (http://mercurial.808500.n3.nabble.com/repository-default-not-found-using-API-td3999339.html) And than we have KeyError: 'bundle' I dont know why mercurial does not set the default for options bundle and force, so we need pass its too: commands.incoming(repo.ui, repo, bundle=None,force=False) Also, You can set hardly your remote repo: commands.incoming(repo.ui, repo, source='default', bundle=None,force=False) For more see lib/site-packages/mercurial/commands.py, hg.py

Categories : Python

python error when cloning a repository with hg/mercurial
This ended up being a version conflict between a custom-compiled Python 2.7.4 and the system-default mercurial (CentOS 6.3). To resolve this issue, I had to empty the PYTHONPATH export PYTHONPATH= The bitbucket checkout eventually worked: destination directory: pycula requesting all changes adding changesets adding manifests adding file changes added 79 changesets with 246 changes to 80 files updating to branch default

Categories : Python

python ast module fails in pydev, succeeds in cmdline python
It seems the ast you have imported in PyDev is not the ast module in the standard library, but a package. I guess: There is a __init__.py file in the same directory as your test1.py. You selected "Add project directory to the PYTHONPATH" during the project creation. These two combined, results in that error. The ast module in the standard library is shadowed by this ast package. In cmdline python, this ast package is not in the search path, thus the ast module is imported. If you change test1.py to import ast if __name__ == '__main__': print ast.__file__ I guess the output in PyDev would be C: esearchastast\__init__.pyc

Categories : Python

Mercurial preoutgoing hook succeeds when a build fails
You are unconditionally running the tests after the build. If the last executed command returns a zero exit code then it will overwrite any non-zero exit code from the previous commands. So you need to check the exit code (ERRORLEVEL in Windows batch) between each command and exit if non-zero. Alternatively, if you want to run the tests even if the build fails, save the exit code and exit with it at the end. To exit immediately: @ECHO OFF %SystemRoot%Microsoft.NETFrameworkv4.0.30319msbuild CaptainHook.sln /m /nr:false /p:Platform="Any CPU" /v:M /fl /flp:LogFile=binmsbuild.log;Verbosity=Normal IF ERRORLEVEL 1 GOTO :EOF %SystemRoot%Microsoft.NETFrameworkv4.0.30319msbuild Tests.sln /m /nr:false /p:Platform="Any CPU" /v:M /fl /flp:LogFile=binmsbuild.log;Verbosity=Normal IF ERRORLEVEL 1 GO

Categories : Batch File

Attribute error: function object has no attribute in python
Just to get this answered: def datapaths(ipaddress, testlogfile): # Unecessary code reomved (code, val) = datapaths.listDatapaths(mylib) # Unecessary code reomved You are trying to access an attribute of a function you've defined, but most likely not set. I think you need to rexamine your code.

Categories : Python

Python trying fails
why arent you using the except keyword try: newbutton['roundcornerradius'] = buttondata['roundcornerradius'] buttons.append(newbutton) except: pass this will try the first part and if an error is thrown it will do the except part you can also add the disered error you want to except a certain error like this except AttributeError: you can also get the excepted error by doing this: except Exception,e: print str(e)

Categories : Python

Python missing image
The problem is that you need to keep your own reference to the PhotoImage you create, or python will garbage collect it, because Tkinter doesn't keep a reference to it. This is either a bug or a feature, depending on your thinking. This code should solve your problem: from Tkinter import * import Image import ImageTk class MyApp: def __init__(self, rData): self.cont1 = Frame(rData) self.cont1.pack(side="top", padx=5, pady=5) self.button1 = Button(rData) self.button1["text"]= "Exit" self.button1["background"] = "red" self.button1.pack(side="bottom",padx=5, pady=5, fill=X) self.button1["command"]= rData.destroy self.picture1 = Label(self.cont1) self.photoImage = ImageTk.PhotoImage(Image

Categories : Python

Python/gtk gtk.gdk.pixbuf_new_from_file() always fails
This works for me: #!/usr/bin/env python # -*- coding: utf-8 -*- import gtk def win_with_image(): pixbuf = gtk.gdk.pixbuf_new_from_file("photo.png") print pixbuf win = gtk.Window(gtk.WINDOW_TOPLEVEL) image = gtk.Image() image.set_from_pixbuf(pixbuf) win.add(image) win.connect("destroy", gtk.main_quit) win.show_all() if __name__ == '__main__': win_with_image() gtk.main() If this doesn`t work for you, try to: start google and type your error and choose the second link (http://aptosid.com/index.php?name=PNphpBB2&file=viewtopic&t=2246), in general this helps almost always. reinstall libglib install gtk (maybe some graphical libs - libpng, libjpeg, f.e.) reinstall python/gtk package fix broken package repository change files permissions

Categories : Python

cron job fails in gae python
I,m pretty sure this error was due to DeadlineExceededError, which I did not run into locally. My scrape() script now does its thing on fewer companies and articles, and does not run into the exceeded deadline.

Categories : Python

Missing output, using range() in Python
range(10, 10, 10) will generate an empty list because range constructs a list from start to stop EXCLUSIVE, so you're asking Python to construct a list starting from 10 going up to 10 but not including 10. There are exactly 0 integers in between 10 and 10 so Python returns an empty list. In [15]: range(10, 10, 10) Out[15]: [] There's nothing to iterate over so nothing will be printed in the loop.

Categories : Python

Application module missing in python
I guess i solved that by downloading a pybindgen folder with the version demanded when running ./waf configure then i put it just above the waf folder and waf automatically gessed it emplacement when running ./waf configure. Now it works for me and I hope it will be the same for you.

Categories : Python

python re.sub missing group name error
dev_line_to_replace probably contains some special characters that have meaning to the regex engine. You should escape devname and dev_line_to_replace using re.escape, to avoid having special characters appear in your search or replace patterns.

Categories : Python

Python package missing when deploying
This is a crappy solution, and I don't like it, but it works. I added this to run.py # Fixing the python path import sys import os file_location = os.path.dirname(os.path.abspath(__file__)) project_dir = os.path.abspath(os.path.join(file_location, os.pardir)) if not project_dir in sys.path: sys.path.insert(0, project_dir)

Categories : Python

Test of db key against url parameter fails (Python)
You problem will be the result of uid = User.by_id_name(linkid) won't be a Userid but a User object. its str method will mean that when you log stuff it looks like a uid but it isn't This means the comparisons will fail. You should be comparing str(uid) == linkid for you code to work. to prove this try logging repr(uid) rather than str(uid)

Categories : Python

Python import value if module fails
A python import statement is an expression just like any other Python code. You can wrap your module import in a try...except block, like so: import somemodule try: from someothermodule import Temperature except ImportError,e: Temperature = 20

Categories : Python

XML parser python fails to get element
If you really have '.config' in the string, that would be the problem. That's a string literal using c as one of its characters. Even if you have '.\config' or r'.config', both of which specify a literal backslash, that would still be wrong: $ cat eleme.py import xml.etree.ElementTree as ET root = ET.fromstring(""" <root> <config> source </config> <config> source </config> </root>""") print r'using .config', root.findall('.config') print r'using .\config', root.findall('.\config') print 'using ./config', root.findall('./config') $ python2.7 eleme.py using .config [] using .\config [] using ./config [<Element 'config' at 0x8017a8610>, <Element 'config' at 0x8017a8650>]

Categories : Python

posting pic with python with twitpic fails
The README.md file (https://github.com/macmichael01/python-twitpic/blob/master/README.md) says ""Command also requires python-2.7 to use.". From the traceback I see your using Python version 2.6. This could be the problem.

Categories : Python

Python defaultdict that does not insert missing values
You can subclass dict and implement __missing__: class missingdict(dict): def __missing__(self, key): return 'default' # note, does *not* set self[key] Demo: >>> d = missingdict() >>> d['foo'] 'default' >>> d {} You could subclass defaultdict too, you'd get the factory handling plus copy and pickle support thrown in: from collections import defaultdict class missingdict(defaultdict): def __missing__(self, key): return self.default_factory() Demo: >>> from collections import defaultdict >>> class missingdict(defaultdict): ... def __missing__(self, key): ... return self.default_factory() ... >>> d = missingdict(list) >>> d['foo'] [] >>> d defaultdict(<type 'list'>,

Categories : Python

How can I find the names of missing parameters in Python?
This has changed in Python3.3 (at most), you get the missing argument names for free: >>> def getVolume(length, width, height): ... return length*width*height; ... >>> print(getVolume(height=3, width=3)); Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: getVolume() missing 1 required positional argument: 'length'

Categories : Python

Ignoring a missing file in a for loop- Python
You can use os.path.exists or os.path.isfile to test whether the file exists or not first. Or put your reading statements in a try...except: pass block. for i in range (1,18): if os.path.isfile("galmasksciPHOTOf105w"+str(i)+".fits") and os.path.exists("fittedsciPHOTOf105w"+str(i)+".fits"): img1= pf.getdata("galmasksciPHOTOf105w"+str(i)+".fits") img2= pf.getdata("fittedsciPHOTOf105w"+str(i)+".fits") img3=(img2)[2] newimg=img1/img3 pf.writeto("dividedsciPHOTOf105w"+str(i)+".fits",newimg, clobber=True) OR: for i in range (1,18): try: img1= pf.getdata("galmasksciPHOTOf105w"+str(i)+".fits") img2= pf.getdata("fittedsciPHOTOf105w"+str(i)+".fits") img3=(img2)[2] newimg=img1/img3 pf.writeto("dividedsciPHOTOf105w"+str(i)

Categories : Python

Missing dll Error Whle installing Python 2.7
Was facing the same problem in windows 8 - 64 bit .. try doing this.. Go to C:/Users//AppData/Local . right click on the folder "Temp". Go to Properties. Go to Security Tab. Click on "Everyone" and "Edit" the permission to "full control"-> allow. Click apply. try running the installer again. YOu should be good to go.

Categories : Python

Python winreg missing subkey on Win7
Once I figured out this problem is related to 64/32 bit windows redirection is was pretty easy to get around. I had to use the following to get registry values from 64 bit hosts. key = winreg.OpenKey(aReg, subkey, 0, (winreg.KEY_WOW64_64KEY + winreg.KEY_READ)) (www.stackoverflow.com/ questions/ 8506646/ change-64bit-registry-from-32bit-python) This site has pretty simple explanation what's happening: python.6.x6.nabble.com/ Seven-64bits-and-system32-syswow64-paths-td4540789.html "On a 64-bit system all of the 64-bit commands and DLLs live under windowssystem32 and all of the 32-bit commands and DLLs live under windowsSysWOW64. 64 bit process gets to see both of those directories as they are but for 32-bit process the operating system rewrites paths and when referring to windowssyste

Categories : Python

Missing en_US locale required for python
try to add the 'utf8' bit as well; import locale locale.getlocale() >>> (None, None) locale.setlocale(locale.LC_ALL, 'en_US.utf8') >>> 'en_US.utf8' locale.getlocale() >>> ('en_US', 'UTF-8')

Categories : Python

Python 2.7.5 on Cygwin64: requests installation fails
Also ran into the same issues when trying to install requests, all the options on http://docs.python-requests.org/en/latest/user/install/#install did not work. I went to https://github.com/kennethreitz/requests and then clicked on "Download Zip" and I got requests-master.zip.

Categories : Python

Python Multiprocess using Pool fails on AWS Ubuntu
The MemoryError means you're running out of system-wide virtual memory. How much virtual memory you have is an abstract thing, based on the actual physical RAM plus swapfile size plus stuff that's paged into memory from other files and stuff that isn't paged anywhere because the OS is being clever and so on. According to your comments, each process averages 0.75GB of real memory, and 4GB of virtual memory. So, your total VM usage is 32GB. One common reason for this is that each process might peak at 4GB, but spend almost all of its time using a lot less than that. Python rarely releases memory to the OS; it'll just get paged out. Anyway, 6GB of real memory is no problem on an 8GB Mac or a 7GB c1.xlarge instance. And 32GB of VM is no problem on a Mac. A typical OS X system has virtually

Categories : Python

How can you cleanup a Python UnitTest when setUpClass fails?
The same way you protect resources elsewhere. try-except: def setUpClass(cls): # ... acquire resources try: # ... some call that may fail except SomeError, e: # cleanup here Cleanup could be as simple as calling cls.tearDownClass() in your except block. Then you can call assert(False) or whatever method you prefer to exit the test early.

Categories : Python

Python to JSON Serialization fails on Decimal
It is not (no longer) recommended you create a subclass; the json.dump() and json.dumps() functions take a default function: def decimal_default(obj): if isinstance(obj, decimal.Decimal): return float(obj) raise TypeError json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default) Demo: >>> def decimal_default(obj): ... if isinstance(obj, decimal.Decimal): ... return float(obj) ... raise TypeError ... >>> json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default) '{"x": 5.5}' The code you found only worked on Python 2.6 and overrides a private method that is no longer called in later versions.

Categories : Python

asciidoc fails when called via python subprocess
Try this: asciidoc_call = ["asciidoc","-b", "docbook45", asciidoc_file_name] the other call would call ascidoc with "-b docbook45" as one single option, which won't work.

Categories : Python

Python 3 script using libnotify fails as cron job
You are in the right track. This behavior is because cron is run in a multiuser headless environment (think of it as running as root in a terminal without GUI, kinda), so he doesn't know to what display (X Window Server session) and user target to. If your application open, for example, windows or notification to some user desktop, then this problems is raised. I suppose you edit your cron with crontab -e and the entry looks like this: m h dom mon dow command Something like: 0 5 * * 1 /usr/bin/python /home/foo/myscript.py Note that I use full path to Python, is better if this kind of situation where PATH environment variable could be different. Then just change to: 0 5 * * 1 export DISPLAY=:0 && /usr/bin/python /home/foo/myscript.py If this still doesn't work you need to

Categories : Python

Python SAX parser fails to handle  character
Although you can encode these characters, they're still at best "frowned upon". See http://www.w3.org/TR/xml/#NT-Char for a list of "bad" characters. Then, see this 1.1 spec as well, which adds some back as allowed in some cases, as "restricted" characters. If the text legitimately should be able to include these characters, it's wise to encode it first, e.g., with base64 encoding. The receiver thus gets well-formed XML (for XML 1.1, it's not always required but that will make it compatible with 1.0). I had to deal with externally-supplied invalid XML myself once before, where I had no control over the sender. It's pretty messy. In my case I could rely on certain patterns, and hence use regular expressions to "patch away" improprieties, but this is a hack: a workaround done out of d

Categories : Python

Python relative import fails in Maya
as long as Prod is on the python path, you can do this - the safest way, using absolute paths # in PAMod2.py import Prod.PackA.PAMod1 Prod.PackA.PAMod1.Function() or (still safe, easier to type): # in PAMod2.py import Prod.PackA.PAMod1 as Mod1 Mod1.Function() You can reference a sibling package as well. This only works inside a module - you can'd do it interactively ( ie, from the maya script editor) . It's also a going to break if eather PackA or PackB moves # in PAMod2.py from .. import PAMod1 PAMod1.Function() The python docs are here and this is a good SO question on the same (common) topic

Categories : Python

Python RegEx query missing overlapping substrings
From the Python 3 documentation (emphasis added): $ python3 -c 'import re; help(re.findall)' Help on function findall in module re: findall(pattern, string, flags=0) Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. If you want overlapping instances, use regex.search() in a loop. You have to compile the regular expression because the API for non-compiled regular expressions doesn't take a parameter to specify the starting position. def findall_overlapping(pattern, string, flags=0): """Find all matches, even ones that overlap.""" regex = re.compile(pa

Categories : Regex

How to install a missing python package from inside the script that needs it?
Thanks to @Joop I was able to come-up with the proper answer. try: import zumba except ImportError: import pip pip.main(['install', '--user', 'zumba']) import zumba One important remark is that this will work without requiring root access as it will install the module in user directory. Not sure if it will work for binary modules or ones that would require compilation, but it clearly works well for pure-python modules. Now you can write self contained scripts and not worry about dependencies.

Categories : Python

Insert Missing Month Values as 0 in Python List
I think a simpler solution is to just iterate through the months and years in the range, and add the ones that are missing. This would be easier if you used a dict instead of a list of two-element lists, so let's do that first. data = dict(t) for year in range(2012, 2014): for month in range(1, 13): mmyyyy = '{:02}-{:04}'.format(month, year) data.setdefault(mmyyyy, 0) Then, if you want to convert it back to your original format, that's easy too: t = [[k, v] for k, v in data.items()] And if you need them sorted by date… Well, your month-first format makes that ugly, but it's certainly doable: t = sorted(t, key=lambda kv: kv[0][3:] + kv[0][:2]) But, as that last line shows, it's often a whole lot easier to deal with dates as date objects rather than stri

Categories : Python

Correct way to check for empty or missing file in Python
os.path.exists and other functions in os.path. As for reading, you want something like if not os.path.exists(path): with open(path) as fi: if not fi.read(3): #avoid reading entire file. print "File is empty"

Categories : Python

python & gtk3 - cairo_context.show_layout method is missing
I was wrong rectangle is present in cairo.Context but not in pango.Context I used pango.Context because I couldn't find show_layout in cairo.Context Now I see the method is not in pango.Context object either We have to use unbounded method PangoCairo.show_layout Summary: cr = self.get_window().cairo_create() cr.rectangle(0, 0, w, h) PangoCairo.show_layout(cr, layout)

Categories : Python

Python dict deserialization works in python2.7, fails in 3.3
According to Python 3 json module documentation: The json module always produces str objects, not bytes objects. ... According to Python 3 sqlite3.register_converter documentation: Registers a callable to convert a bytestring from the database into a custom Python type. ... If you try to load bytesstring json, you get TypeError: >>> json.loads('"0"') '0' >>> json.loads(b'"0"') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.3/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/usr/lib/python3.3/json/decoder.py", line 352, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: can't use a string pattern on a bytes-like object You should convert

Categories : Python

PowerPoint & Python: Editing PPT fails when an image is reached
While your code is not actually working replacing your if with a try catch works fine. This may not be a elegant method tough. import win32com.client, sys Application = win32com.client.Dispatch("PowerPoint.Application") Application.Visible = True Presentation = Application.Presentations.Open(sys.argv[1]) for Slide in Presentation.Slides: for Shape in Slide.Shapes: try: Shape.TextFrame.TextRange.Font.Name = "Arial" Shape.TextFrame.TextRange.Font.Size = "12" Shape.TextFrame.TextRange.Font.Color.RGB = "000000" except: pass Presentation.Save() Application.Quit() What probably happens to you is that the if is always true since an object qualifies as true. Try asking length of the object greater than 0 or something similar.

Categories : Python

parallel installion of Python 2.7 and 3.3 via Homebrew - pip3 fails
I was having the same problem as you were and I had export PYTHONPATH="/usr/local/lib/python2.7/site-packages:$PYTHONPATH" in my ~/.bash_profile. Removing that line solved the problem for me. If you have that or something like it in your ~/.bashrc or ~/.bash_profile, try removing it.

Categories : Python

Python's os.walk() fails in Windows when there are long filenames
In Windows file names (including path) can not be greater than 255 characters, so the error you're seeing comes from Windows, not from Python - because somehow you managed to create such big file names, but now you can't read them. See this post for more details.

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.