w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Python failure file handling freeze
Remove the blanket except. Your script is not freezing, but any error you get is being ignored in an endless loop. Because you use a blanket except: you catch all exceptions, including the keyboard interrupt exception KeyboardInterrupt. At the very least log the exception, and catch only Exception: except Exception: import logging logging.exception('Oops: error occurred') KeyboardInterrupt is a subclass of BaseException, not Exception and won't be caught by this except handler. Take a look at the shutil module for copying files, you doing way too much work: import time import shutil import os.path paths = ('28-000004d2ca5e', '28-000004d2fb20', '28-000004d30568') while True: for i, name in enumerate(paths, 1): src = os.path.join('/sys/bus/w1/devices', name, 'w1_

Categories : Python

Python cx-freeze issue
You're using wrong command: freeze.py in pip/commands directory is for pip freeze command. Use cxfreeze program. cxfreeze /home/frost/Desktop/dd.py See cxfreeze script for usage detail.

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

Python list is converted into integer
self.__vector = [self.__vector + vector.__vector for self.__vector, vector.__vector in zip(self.__vector, vector.__vector)] See that? You're assigning values to self.__vector, vector.__vector in the loop for self.__vector, vector.__vector in zip(self.__vector, vector.__vector).

Categories : Python

" is converted to \" while saving the string to dictionary in python
You are looking at the repr() representation of a string. This is normal. A string representation uses escape codes for non-printable characters or anything that requires escaping. Python containers show their contents, when printed, as string representations for debugging purposes. The resulting string representation is re-usable as a string literal, you can paste that right back into Python and it'll produce the same value. Print individual values of you want to see the output unescaped: print temp["key"] and if you feel so inclined, compare that with the repr() result of the string: print repr(temp["key"])

Categories : Python

efrc gives error length-1 array can be converted to python
cmath does not support numpy arrays: BER2=(3/8)*erfc(sqrt(ebno*(2/5)))+(1/4)*erfc(3*sqrt(2/5*ebno)) You seem to be importing a lot of functions as from foo import * this can really trip you up. Also you are using ints (for example 2/5) instead of floats so the equation above just returns an array of all zero's: >>> 2/5 0 >>> 2./5 0.4 I suggest: >>> import numpy as np >>> import scipy.special as sp >>> EbbyNo=np.arange(0.,16.,1) >>> ebno=10**(EbbyNo/10) >>> BER2=(3./8)*sp.erfc(np.sqrt(ebno*(2./5)))+(1./4)*sp.erfc(3*np.sqrt(2./5*ebno)) >>> BER2 array([ 1.40982603e-01, 1.18997473e-01, 9.77418560e-02, 7.74530603e-02, 5.86237373e-02, 4.18927600e-02, 2.78713278e-02, 1.69667344e-02, 9.247

Categories : Python

TypeError: not all arguments converted during string formatting python
You're mixing different format functions. The old-style % formatting uses % codes for formatting: 'It will cost $%d dollars.' % 95 The new-style {} formatting uses {} codes and the .format method 'It will cost ${0} dollars.'.format(95) Note that with old-style formatting, you have to specify multiple arguments using a tuple: '%d days and %d nights' % (40, 40) In your case, since you're using {} format specifiers, use .format: "'{0}' is longer than '{1}'".format(name1, name2)

Categories : Python

I converted CAF to AAC format using TPAACAudioConverter but converted file duration is 0
Can you playback the caf file ? If you only want to record a sound from microphone to an aac file, you can use Audio Queue Services (I can post some code) Edit : it's an implementation from Apple dev tutorial, there might be some errors since I modified it to fit your question //AudioQ.mm @implementation AudioQ static const int nBuffer = 3; struct AQRecorderState{ AudioStreamBasicDescription mDataFormat; AudioQueueRef mQueue; AudioQueueBufferRef mBuffers[nBuffer]; AudioFileID mAudioFile; UInt32 bufferByteSize; SInt64 mCurrentPacket; bool mIsRunning; }; AQRecorderState aqData; CFURLRef url; static OSStatus BufferFilledHandler(

Categories : Iphone

Python compile all modules into a single python file
You can simply include .pyc files for the libraries required, but no - .pyc cannot work as a container for multiple files (unless you will collect all the source into one .py file and then compile it).

Categories : Python

Run python file within python script, passing arguments
I would try doing somehting like this. os.system("appcfg.py arg1 arg2 arg3") I would look into this portion of the os documentation. Goodluck.

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

can't concatenate string with .join using python. TypeError: not all arguments converted during string formatting
use temporary variable to save your string like: temp = "INSER INTO users(" + ",".join(rows_names) + ") VALUES(" + test2 + ")" temp = temp % (name, val, 'SomeNickname', 'password', '13-09-11', '2', '@gmail.com','1') and then interpolate data into it or add additional parentheses around ("INSER INTO users(" + ",".join(rows_names) + ") VALUES(" + test2 + ")") it will look like temp = ("INSER INTO users(" + ",".join(rows_names) + ") VALUES(" + test2 + ")") % (name, val, 'SomeNickname', 'password', '13-09-11', '2', '@gmail.com','1') problem is that you didn't have complete string, and wanted to insert data into ")"

Categories : Python

Can't execute python script from php
Your problem is this: When launching the php script through the console, you are launching php with the permissions of your current user. When a process is executed through opening it in the browser, it will have the permissions of the user of your web-server-process. Your group permissions will have to be 7 no matter what. Either change the python scripts permissions to 777 (read-write-execute for everybody) or change it to 770 and make sure that your web-servers user is inside the group set to the file.

Categories : PHP

Python: Why does this code execute?
This is the output I get: 1 2 2 1 3 0 4 -1 5 -2 6 -3 7 -4 8 -5 9 -6 10 -7 Your question as to why it runs. Your outer most conditional is a while loop, which is true upon the first execution, however it runs right into a nested for loop. When this happens the while, will not be checked until the for loop finishes its first execution (which is why p = -7). What you want is this: p = 2 for i in range(10): if p <= 0: break print i+1 , p p-=1 which gives output: 1 2 2 1

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

Execute python script in localhost
Google App Engine SDK for Python includes a local web server application that simulates the App Engine environment. It allows for instant server script changes by just saving the file and refreshing the browser. The development tutorial is here Once you have your web site working locally, it is easy to deploy it live on Google's App Engine servers.

Categories : Python

How to execute awk command by python code
While I agree that this is actually best done in Python, rather than invoking awk. If you really need to do this, then the actual error is with your awk. #!/usr/bin/env python import subprocess as sp args = ["awk", r'{OFS=" "; print $2,$4,$5,$6}', "B3LYPD.txt"] p = sp.Popen(args, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE ) print(p.readline()) # will give you the first line of the awk output Edit: Fixed missing quote.

Categories : Python

Python: rasing from except causes finally to execute?
finally is executed no matter the try block succeeds or the except block is run due to exceptions! even if your except block raises an exception the new exception will be handled by another try catch handler but after executing the finally block, instead of forming a recursive loop: try: try: [...] except: raise Exception([...]) #this is line number xyz finally: [code] except: [...] #this code will be running after line number xyz

Categories : Python

Execute .sql schema in psycopg2 in Python
You can just use execute: with self.connection as cursor: cursor.execute(open("schema.sql", "r").read()) though you may want to set psycopg2 to autocommit mode first so you can use the script's own transaction management. It'd be nice if psycopg2 offered a smarter mode where it read the file in a statement-at-a-time and sent it to the DB, but at present there's no such mode as far as I know. It'd need a fairly solid parser to do it correctly when faced with $$ quoting (and its $delimiter$ variant where the deimiter may be any identifier), standard_conforming_strings, nested function bodies, etc. Note that this will not work with: anything containing psql backslash commands COPY .. FROM STDIN ... and therefore won't work with dumps from pg_dump

Categories : Python

How to execute commands through pipe in Python?
Piping is a shell function. Therefore your Popen call needs shell=True on it. Otherwise your | wc is going to be passed to find, which won't know what to do with it (and is probably sending an error to that effect into err... which you're not printing). But why shell out at all? Just do all that stuff in Python (e.g. os.walk to replace find) It'll be easier to read and maintain. Something like: import os, re for dirpath, dirnames, filenames in os.walk(rootpath): for filename in filenames: if filename.endswith(".cc"): with open(os.path.join(dirpath, filename)) as infile: text = infile.read() chars = len(text) lines = sum(1 for x in re.finditer(r" ", text)) lines += not text.endswith(" ") # count last

Categories : Python

execute main through if condition in python
Make it an independent function. def run_main(): .... if __name__ == "__main__": run_main() And you can call run_main() from another file.

Categories : Python

Execute python in a php script using shell_exec()
I think kernel not able to find the path for python where it is installed..if you can do echo $PATH..it will show all the paths where to be search a command if given add your python part there and then it may work or you can give absolute path(other than /usr/bin/) see if it works..I need to test it too.

Categories : PHP

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

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

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

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

crontab doesn't execute my python script
First, you have an odd indentation in the line with if __name__ ==... - guess you should check it in your script. Then, make sure with what current directory your script runs, AFAIK it is your $HOME - this is where the file would appear.

Categories : Python

Execute python script using urllib2 from PHP behind Proxy
You could try passing explicit proxy settings to your Python script to see if that clears up the problem for you. I recently wrote a script that allows you to set proxy settings with command line arguments that might be useful for this case. The important parts of the script are below: # Import the required libraries from urllib import urlencode from urllib2 import Request, urlopen, URLError, ProxyHandler, build_opener, install_opener import argparse # Set up our argument parser parser = argparse.ArgumentParser(description='Does stuff through a proxy') parser.add_argument('webAddr', type=str, help='Web address of target server') parser.add_argument('--proxServ', metavar='SERV', type=str, help='Web address of proxy server, i.e. http://proxy.server.com:80') parser.add_argument('--proxType'

Categories : PHP

In Python, how do you execute objects that are functions from a list?
Make all of them lists and then iterate over the list executing each in turn. for actionVal,actionDesc,actionFunctions in validActions: if ctx["newAction"] == actionVal: for actionFunction in actionFunctions: actionFunction()

Categories : Python

Execute Shell Script from python with variable
Like this ? subprocess.call(['test.sh', str(domid)]) Documentation is available on the python website

Categories : Python

Execute R script with python subprocess.call
Using commandArgs like this: args <- commandArgs(trailingOnly = TRUE) arg1 <- args[1] arg2 <- args[2] [...your code...] Also make sure that the Rscript executable is in your PATH.

Categories : Python

How to execute code when a Python script is closed out?
import MySQLdb con = MySQLdb.connect(...) cursor = con.cursor() try: # do stuff with your DB finally: con.close() The finally clause is executed on success as well as on error (exception). If you hit Ctrl-C, you get a KeyboardInterrupt exception.

Categories : Python

crontab: python script being run but does not execute OS Commands
Two things: Your cd will set the directory for that subprocess, which immediately exits: subprocess.call(["cd", "/home/atweb/Documents/opengrok"]) In other words, it's a wasted step. The next subprocess doesn't know anything about the previous one's environment: subprocess.call(["./stop_website"]) ...so it won't be able to run. If you want all of your programs to run in that directory, use: os.chdir("/home/atweb/Documents/opengrok") before any of the subprocess.call() lines.

Categories : Python

execute cat command in subprocess,Popen() of python
The problem is that you're passing the command as multiple args. You need to pass them as a list or a tuple. Like: subp.Popen([ 'egrep','list_of_IDs','/home/bimlesh/python/result.log' ], stdout=subp.PIPE,stderr=subp.PIPE,shell=True)

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

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

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



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