w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
python: why does os.makedirs cause WindowsError?
A little googling reveals that this error is raised in various different contexts, but most of them have to do with permissions errors. The script may need to be run as administrator, or there may be another program open using one of the directories that you are trying to use.

Categories : Python

CSS fails with extended paths in Compojure / Hiccup
Your CSS is being included with a relative path, which means the when you go to localhost:3000/article-list/article-one your browser is looking for the CSS at localhost:3000/article-list/css/main.css. The easiest way to fix this would be to include the CSS with (include-css "/css/main.css"). The / at the beginning will ensure it always searches for localhost:3000/css/main.css.

Categories : Clojure

Python modules' paths
requests is using an absolute import. You cannot arbitrarily nest packages into other directories and still expect things to work. Instead, add the kennethreitz directory (which should not have a __init__.py file) to your sys.path module search path. That way the requests module will still be importable as a top-level package. Next, you may want to look into Python packaging, dependencies and using a tool like pip or zc.buildout to deploy your code for you. Those tools handle dependencies for you and will install requests as required. See the Python Packaging User Guide for an introduction.

Categories : Python

Relative paths approach (python)
Best practice is to use absolute paths. Use the __file__ path not to change directories, instead use it to calculate a base path to use to build absolute paths. In a top-level module, add: import os.path BASE = os.path.dirname(os.path.abspath(__file__)) and reuse BASE to build absolute paths: abspath = os.path.join(BASE, relpath) Changing the working directory is rarely needed or useful.

Categories : Python

Using jQuery, relative paths within a div are updated to absolute paths but having trouble rewriting it to be more dynamic
var foo = { '/catalog.php':'http://www.mydomain.com', '/upgrade':'http://www.mydomain2.com' }; $.each(foo,function (search,prefix) { $('#landing-page').find('a[href^="' + search + '"]').each(function(element, index){ $(this).attr('href',prefix + $(this).attr('href')); }); }); http://jsfiddle.net/U9RXL/1/

Categories : Jquery

Installing Python 3.3 on Mac, links or paths issue
You should remove the mess and install Homebrew instead of Macports. I have never had problems with Homebrew, it's easy to use and just works. It is an other package manager for OS X, which you can install python with just a simple command: brew install python3 This will install pip, so you can easily install packages by: pip install [packagename] I'm not sure about this but you probably need to install the latest Xcode to compile things without problems. This is the easiest, effortless way to install a lot of open source packages to Mac OS X.

Categories : Python

Python and list mutability in an all-paths algorithm
You didn't specify what the symptom is. Is the yielded stuff wrong, or is uniquePaths wrong? It looks like that the function yields the right paths, but at the end of the function, uniquePaths has far fewer paths than it should, and they're all empty. The reason why there's not enough paths, is that uniquePaths.extend(uniqueTreePaths) is not at the right indention. The problem you're here for, is that visited is a mutable list. In Python, all lists are mutable. In fact, that's the reason this algorithm works. visited is treated like a stack that happens to be the path. When you append visited to uniqueTreePaths multiple times, you are really appending the same object over and over again. When you modify visited, all of them are modified. To fix this problem, you should append a copy o

Categories : Python

Adding two or more Python project paths to PYTHONPATH
Well, Python always takes the first occurence of "com" (here in PROJECTA) as the module "com" and doesn't even look for other occurences of "com" if it can't find something inside it. Python doesn't "merge" modules - if you think about it, it makes no sense as the modules can be arbitrarily general and complex. Solution A (normal) Include in PYTHONPATH the directory above the projects and address the modules with the prefix, like e.g. this: from PROJECTA import com as comA from PROJECTB import com as comB from comA.example.sample.projectBBB.srcfiles import pythonfile.py Btw. we are tacitly assuming you have __init__.py files where they should be (i.e. in all directories that should be treated as modules). Solution B (weird) Include in PYTHONPATH the directory above the projects as i

Categories : Python

in python: using a list of file paths with the 'with' keyword
The object of a with statement must be a context manager. So, no, you can't do this with a list, but you might be able to do it with a custom container. See: http://docs.python.org/2/library/contextlib.html Or, for 3.3+ there's this: http://docs.python.org/dev/library/contextlib.html#contextlib.ExitStack (Note, as per arbarnert's answer, this can be used in 2.7, using contextlib2. See his answer for the link.) The actual solution here is probably to If you're not going to use contextlib2 put the context manager in a loop: for path in paths_list: with open(path, 'r') as f: #whatever pass Edit: Obviously, the above will open your files one at a time. There are relatively few use cases where you need to keep an undetermined number of files open at once. Edit: To h

Categories : Python

Open albumdata.xml with python and get all image paths
I used the following code to get all image paths The tricky part is to access the nested dictionaries. Is there a more efficient way to access the nested dictionaries?? import plistlib albumData = plistlib.readPlist("/Users/Darrell/Pictures/iPhoto Library/AlbumData.xml") masterImageList = albumData["Master Image List"] for key, value in masterImageList.items(): print (value['ImagePath']) result: /Users/Darrell/Pictures/iPhoto Library/Masters/2013/08/09/20130809-181038/Kelly.jpg /Users/Darrell/Pictures/iPhoto Library/Masters/2013/08/09/20130809-180444/_DSC1225.jpg /Users/Darrell/Pictures/iPhoto Library/Masters/2013/08/09/20130809-181030/_DSC1268.jpg /Users/Darrell/Pictures/iPhoto Library/Masters/2013/08/09/20130809-181037/_DSC0923.jpg /Users/Darrell/Pictures/iPhoto Library/Masters/

Categories : Python

Python: check if two Linux paths are on same physical disk
Look at the hex output. The first number after the 0x prefix indicates the device driver: >>> hex(os.stat("/usr").st_dev) '0x801L' This is a 'SCSI' disk, because all of them have ID 8. Reference: https://www.kernel.org/doc/Documentation/devices.txt. Drive ID and partition number are encoded in the remaining part of the st_dev. The exact transformation for major ID and minor ID as implemented by glibc is as follows: >>> minor = int(os.stat("/lib").st_dev & 0xff) >>> major = int(os.stat("/lib").st_dev >> 8 & 0xff) >>> major, minor (8, 1) Meaning major number 8 (SCSI host adapter), minor number 1. The minor number encodes drive number as well as partition. As can also be inferred from here, all partitions on the first disk have a minor

Categories : Python

How to sanitize user-provided paths in Python and Flask?
Werkzeug provides secure_filename to help with this, an example is provided in the Flask docs @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) #Sanitised here file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('uploaded_file', filename=filename))

Categories : Python

Converting remote relative paths to absolute paths
I think you would need to use regular expressions on the href path to make sure that it is consistent. You can also get an accurate base url from parse_url(): <?php $href = '../images/sunflower.png'; $href = preg_replace('~^.{0,2}/~', '', $href); ?> Here we strip the periods and the slashes from the beginning of the string. And then prepend the base url: <?php $url = 'http://www.example.com/home/index.html'; $url = parse_url($url); $abspath = $url['scheme'] . '://' . $url['host'] . '/' . $href; echo $abspath; ?> Should output what you want: http://www.example.com/images/sunflower.png UPDATE If you want the first directory from the base url, then use explode on the parsed url's path key: $first_directory = ''; if (isset($url['path'])) { $patharray = explode('/',

Categories : PHP

Python: Adding Variable paths into os.system("open"+filename)
The % operator wants the 'open+%s' string as its left-hand side. You are offering it the return value of os.system(). Also, I think you wanted a space, not a + in the string. Try this: os.system('open %s'%i)

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

Set Enviroment Variable that contains two paths interelated paths
I think an alias is more appropriate for all kinds like this (you may consider a more suitable name for the alias) alias var="/usr/bin/python2.7 /home/user/file" If you want to stick with your version you have to tell your shell to evaluate the content of VAR. For this you just have to invoke eval ${VAR} By the way, why do you append the string "/usr/bin/python2.7 /home/user/file" to VAR instead of overwriting the content of VAR?

Categories : Linux

Local paths for the files are different from the paths on the server
When you're writing an asp.net application, the most important path you need to be aware of is the following one: ~/ This will always return the root of the current application, whether you pass it to Response.Redirect(), Page.ResolveUrl() or use it as part of your hyperlink in an <asp:hyperlink /> tag. For example: <link href='<%= Page.ResolveUrl("~/somepath/file.css") %>' rel='stylesheet' /> Note that this only works within code handled by .net itself; for other files, you need to ensure that you always use relative paths. So for example if you have the following structure for your images and css: / /images logo.gif /css main.css then you reference the logo using the style: { background-image: url(../images/logo.gif); }

Categories : Asp Net

Relative paths break when executing Python script from Windows batch?
Yes, that is logical. The files are relative to your working directory. You change that by running the script from a different directory. What you could do is take the directory of the script you are running at run time and build from that. import os def read_file(filename): #get the directory of the current running script. "__file__" is its full path path, fl = os.path.split(os.path.realpath(__file__)) #use path to create the fully classified path to your data full_path = os.path.join(path, filename) with open(full_path, "r") as file: #etc

Categories : Python

Finding shortest paths with python-IGraph on DAGs with negative weights
get_shortest_paths is not able to handle graphs with negative weights because the underlying C library does not have a corresponding igraph_get_shortest_paths_bellman_ford function yet. It does have an igraph_get_shortest_paths_dijkstra, so the Python interface simply checks whether you have weights and if so, redirects the call to igraph_get_shortest_paths_dijkstra, otherwise it simply calls igraph_get_shortest_paths (which is the unweighted version in the C layer). In contrast, shortest_paths works with negative weights because the C library has a function named igraph_shortest_paths_bellman_ford so it calls the Bellman-Ford implementation when at least one of the edge weights is negative. Unfortunately the only way out seems to be to implement igraph_get_shortest_paths_bellman_ford in

Categories : Python

Visual Studio: Differences between image paths set from the project window and programmatically set image paths
In first instance images are stored as a resouce file and are saved in the resources. Whereas in the second instance you specify the path where the image resides. Yes you can add image in resources progamatically if you are working in .net 4 or above. See this for details.

Categories : C#

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/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

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

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 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 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

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 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

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 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

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 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

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

Python/Pyside: Own QFileIconProvider implementation fails with no exceptions thrown
I solved the problem by myself now....kinda :D I used to go another way and wrote my own QFileSystemModel class. Then i have overwritten the data method and returned my own Icons. My code looks like the following: class SeFileSystemModel(QtGui.QFileSystemModel): def __init__(self): QtGui.QFileSystemModel.__init__(self) self.fileEndPattern = re.compile("^.*.(w{2,4})$") def data(self, index, role): if index.column() == 0 and role == QtCore.Qt.DecorationRole: if self.fileEndPattern.match(index.data()) is not None: if index.data().endswith('rs'): return QtGui.QIcon(':icons/rs-file.png') return QtGui.QIcon(':icons/newfile.png') return QtGui.QIcon(':icons/openFolder.png') return super(SeFileSystemModel, self).data(inde

Categories : Python



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