Search Results

Search found 14486 results on 580 pages for 'python idle'.

Page 44/580 | < Previous Page | 40 41 42 43 44 45 46 47 48 49 50 51  | Next Page >

  • Why is Python 3.1.3 in the header listed as a syntax error?

    - by squashua
    Hi, I'm a newbie programmer so I'll do my best to clearly ask my question. I'm running Python scripts in Mac 10.6.5 and now trying to write and save to a text file (following instructions in HeadsUp Python book). Whenever I hit function+F5 (as instructed) I get the same "invalid syntax" error and Idle highlights the "1" in "Python 3.1.3" of the header. Here's the header to which I'm referring: Python 3.1.3 (r313:86882M, Nov 30 2010, 09:55:56) [GCC 4.0.1 (Apple Inc. build 5494)] on darwin Type "copyright", "credits" or "license()" for more information. Extremely frustrating. I've checked and rechecked the code but this doesn't seem to be code related because the "syntax error" is in regards to the header text that posts in every Idle/Python session. Help anyone? Thanks, Squash

    Read the article

  • PYTHON: ntlm authentication

    - by Svetlana
    Hello!! I'm trying to implement NTLM authentication on IIS (Windows Server 2003) from Windows 7 with python. LAN Manager Authentication Level: Send NTLM response only. Client machine and server are in the same domain. Domain controller (AD) is on another server (also running Windows Server 2003). I recieve 401.1 - Unauthorized: Access is denied due to invalid credentials. Could you please help me find out what is wrong with this code and/or show me the other possible directions to solve this problem (using NTLM or Kerberos)? [python] import sys, httplib, base64, string import urllib2 import win32api import sspi import pywintypes import socket class WindoewNtlmMessageGenerator: def __init__(self,user=None): import win32api,sspi if not user: user = win32api.GetUserName() self.sspi_client = sspi.ClientAuth("NTLM",user) def create_auth_req(self): import pywintypes output_buffer = None error_msg = None try: error_msg, output_buffer = self.sspi_client.authorize(None) except pywintypes.error: return None auth_req = output_buffer[0].Buffer auth_req = base64.encodestring(auth_req) auth_req = string.replace(auth_req,'\012','') return auth_req def create_challenge_response(self,challenge): import pywintypes output_buffer = None input_buffer = challenge error_msg = None try: error_msg, output_buffer = self.sspi_client.authorize(input_buffer) except pywintypes.error: return None response_msg = output_buffer[0].Buffer response_msg = base64.encodestring(response_msg) response_msg = string.replace(response_msg,'\012','') return response_msg fname='request.xml' request = file(fname).read() ip_host = '10.0.3.112' ntlm_gen = WindoewNtlmMessageGenerator() auth_req_msg = ntlm_gen.create_auth_req() auth_req_msg_dec = base64.decodestring(auth_req_msg) auth_req_msg = string.replace(auth_req_msg,'\012','') webservice = httplib.HTTPConnection(ip_host) webservice.putrequest("POST", "/idc/idcplg") webservice.putheader("Content-length", "%d" % len(request)) webservice.putheader('Authorization', 'NTLM'+' '+auth_req_msg) webservice.endheaders() resp = webservice.getresponse() resp.read() challenge = resp.msg.get('WWW-Authenticate') challenge_dec = base64.decodestring(challenge.split()[1]) msg3 = ntlm_gen.create_challenge_response(challenge_dec) webservice = httplib.HTTP(ip_host) webservice.putrequest("POST", "/idc/idcplg?IdcService=LOGIN&Auth=Intranet") webservice.putheader("Host", SHOD) webservice.putheader("Content-length", "%d" % len(request)) webservice.putheader('Authorization', 'NTLM'+' '+msg3) webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"") webservice.putheader("SOAPAction", "\"\"") webservice.endheaders() webservice.send(request) statuscode, statusmessage, header = webservice.getreply() res = webservice.getfile().read() res_file = file('result.txt','wb') res_file.write(res) res_file.close() [/python] sspi.py is available here: http://www.koders.com/python/fidF3B0061A07CD13BA35FF263E3E45252CFABFAA3B.aspx?s=timer Thanks!

    Read the article

  • Python coding test problem for interviews

    - by Kal
    I'm trying to come up with a good coding problem to ask interview candidates to solve with Python. They'll have an hour to work on the problem, with an IDE and access to documentation (we don't care what people have memorized). I'm not looking for a tough algorithmic problem - there are other sections of the interview where we do that kind of thing. The point of this section is to sit and watch them actually write code. So it should be something that makes them use just the data structures which are the everyday tools of the application developer - lists, hashtables (dictionaries in Python), etc, to solve a quasi-realistic task. They shouldn't be blocked completely if they can't think of something really clever. We have a problem which we use for Java coding tests, which involves reading a file and doing a little processing on the contents. It works well with candidates who are familiar with Java (or even C++). But we're running into a number of candidates who just don't know Java or C++ or C# or anything like that, but do know Python or Ruby. Which shouldn't exclude them, but leaves us with a dilemma: On the one hand, we don't learn much from watching someone struggle with the basics of a totally unfamiliar language. On the other hand, the problem we use for Java turns out to be pretty trivial in Python (or Ruby, etc) - anyone halfway competent can do it in 15 minutes. So, I'm trying to come up with something better. Surprisingly, Google doesn't show me anyone doing something like this, unless I'm just too dumb to enter the obvious search term. The best idea I've come up with involves scheduling workers to time slots, but it's maybe a little too open-ended. Have you run into a good example? Or a bad one? Or do you just have an idea?

    Read the article

  • How to implement Priority Queues in Python?

    - by dragosrsupercool
    Sorry for such a silly question but Python docs are confusing.. . Link 1: Queue Implementation http://docs.python.org/library/queue.html It says thats Queue has a contruct for priority queue. But I could not find how to implement it. class Queue.PriorityQueue(maxsize=0) Link 2: Heap Implementation http://docs.python.org/library/heapq.html Here they says that we can implement priority queues indirectly using heapq pq = [] # list of entries arranged in a heap entry_finder = {} # mapping of tasks to entries REMOVED = '<removed-task>' # placeholder for a removed task counter = itertools.count() # unique sequence count def add_task(task, priority=0): 'Add a new task or update the priority of an existing task' if task in entry_finder: remove_task(task) count = next(counter) entry = [priority, count, task] entry_finder[task] = entry heappush(pq, entry) def remove_task(task): 'Mark an existing task as REMOVED. Raise KeyError if not found.' entry = entry_finder.pop(task) entry[-1] = REMOVED def pop_task(): 'Remove and return the lowest priority task. Raise KeyError if empty.' while pq: priority, count, task = heappop(pq) if task is not REMOVED: del entry_finder[task] return task raise KeyError('pop from an empty priority queue' Which is the most efficient priority queue implementation in python? And how to implement it?

    Read the article

  • Fitting Gaussian KDE in numpy/scipy in Python

    - by user248237
    I am fitting a Gaussian kernel density estimator to a variable that is the difference of two vectors, called "diff", as follows: gaussian_kde_covfact(diff, smoothing_param) -- where gaussian_kde_covfact is defined as: class gaussian_kde_covfact(stats.gaussian_kde): def __init__(self, dataset, covfact = 'scotts'): self.covfact = covfact scipy.stats.gaussian_kde.__init__(self, dataset) def _compute_covariance_(self): '''not used''' self.inv_cov = np.linalg.inv(self.covariance) self._norm_factor = sqrt(np.linalg.det(2*np.pi*self.covariance)) * self.n def covariance_factor(self): if self.covfact in ['sc', 'scotts']: return self.scotts_factor() if self.covfact in ['si', 'silverman']: return self.silverman_factor() elif self.covfact: return float(self.covfact) else: raise ValueError, \ 'covariance factor has to be scotts, silverman or a number' def reset_covfact(self, covfact): self.covfact = covfact self.covariance_factor() self._compute_covariance() This works, but there is an edge case where the diff is a vector of all 0s. In that case, I get the error: File "/srv/pkg/python/python-packages/python26/scipy/scipy-0.7.1/lib/python2.6/site-packages/scipy/stats/kde.py", line 334, in _compute_covariance self.inv_cov = linalg.inv(self.covariance) File "/srv/pkg/python/python-packages/python26/scipy/scipy-0.7.1/lib/python2.6/site-packages/scipy/linalg/basic.py", line 382, in inv if info>0: raise LinAlgError, "singular matrix" numpy.linalg.linalg.LinAlgError: singular matrix What's a way to get around this? In this case, I'd like it to return a density that's essentially peaked completely at a difference of 0, with no mass everywhere else. thanks.

    Read the article

  • Python: How to execute a SQL file or command

    - by Mestika
    Hi, I have this Python script: import sys import getopt import timeit import random import os import re import ibm_db import time from string import maketrans runs=5 queries=50 file = open("results.txt", "a") for r in range(5): print "Run %s\n" % r os.system("python reads.py -r1 -pquery1.sql -q50 -sespec") file.write('END QUERY READ 01') file.close() os.system("python query_read_02.py") Everything here is working, it is creating the results.txt file, it run the os.system("python reads.py...") file and that file is doing everything it's suppose to, but the problem comes when go and run the query_read_02.py file. In this file, it should execute a SQL command or a SQL file on my database, so I can create an index and see what the performance of that input is, but how do i do it? I create the connection to the database in the reads.py file, but it's hard to create the queries in there because I doesn't keep track of which file it has reached, it just execute commands from what the parameters are. I hope I've explained myself clear enough, otherwise please let me know. I just want to execute a SQL command or file which each query_read_0x.py file. Sincerely Mestika

    Read the article

  • Asynchronous background processes in Python?

    - by Geuis
    I have been using this as a reference, but not able to accomplish exactly what I need: http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python/92395#92395 I also was reading this: http://www.python.org/dev/peps/pep-3145/ For our project, we have 5 svn checkouts that need to update before we can deploy our application. In my dev environment, where speedy deployments are a bit more important for productivity than a production deployment, I have been working on speeding up the process. I have a bash script that has been working decently but has some limitations. I fire up multiple 'svn updates' with the following bash command: (svn update /repo1) & (svn update /repo2) & (svn update /repo3) & These all run in parallel and it works pretty well. I also use this pattern in the rest of the build script for firing off each ant build, then moving the wars to Tomcat. However, I have no control over stopping deployment if one of the updates or a build fails. I'm re-writing my bash script with Python so I have more control over branches and the deployment process. I am using subprocess.call() to fire off the 'svn update /repo' commands, but each one is acting sequentially. I try '(svn update /repo) &' and those all fire off, but the result code returns immediately. So I have no way to determine if a particular command fails or not in the asynchronous mode. import subprocess subprocess.call( 'svn update /repo1', shell=True ) subprocess.call( 'svn update /repo2', shell=True ) subprocess.call( 'svn update /repo3', shell=True ) I'd love to find a way to have Python fire off each Unix command, and if any of the calls fails at any time the entire script stops.

    Read the article

  • Activate a python virtual environment using activate_this.py in a fabfile on Windows

    - by Rudy Lattae
    I have a Fabric task that needs to access the settings of my Django project. On Windows, I'm unable to install Fabric into the project's virtualenv (issues with Paramiko + pycrypto deps). However, I am able to install Fabric in my system-wide site-packages, no problem. I have installed Django into the project's virtualenv and I am able to use all the " python manage.py" commands easily when I activate the virtualenv with the "VIRTUALENV\Scripts\activate.bat" script. I have a fabric tasks file (fabfile.py) in my project that provides tasks for setup, test, deploy, etc. Some of the tasks in my fabfile need to access the settings of my django project through "from django.conf import settings". Since the only usable Fabric install I have is in my system-wide site-packages, I need to activate the virtualenv within my fabfile so django becomes available. To do this, I use the "activate_this" module of the project's virtualenv in order to have access to the project settings and such. Using "print sys.path" before and after I execute activate_this.py, I can tell the python path changes to point to the virtualenv for the project. However, I still cannot import django.conf.settings. I have been able to successfully do this on *nix (Ubuntu and CentOS) and in Cygwin. Do you use this setup/workflow on Windows? If so Can you help me figure out why this wont work on Windows or provide any tips and tricks to get around this issue? Thanks and Cheers. REF: http://virtualenv.openplans.org/#id9 | Using Virtualenv without bin/python Local development environment: Python 2.5.4 Virtualenv 1.4.6 Fabric 0.9.0 Pip 0.6.1 Django 1.1.1 Windows XP (SP3)

    Read the article

  • mysql-python stopped working

    - by MAC
    This is a rather dumb question but i'am looking at a bizarre situation. I am running fedora and have python 2.6.5 installed. The other day i installed MySQL-python using yum (because i do not have the setuptools module so i cannot build it from source). Anyway yesterday i wrote my entire data access layer in python and it was running fine, i did test it. Today however it gives me an ImportError: No module named MySQLdb The only thing i ever changed was i installed eclipse and pyDev. Any ideas on what went wrong and how i fix it. I tried removing and re-installing MySql-python but that did not help. I did the following import sys print sys.path And it shows me all the paths which are basically pertaining to /usr/local/lib/python2.6 However i was trying to find where the MySQLdb module is installed and it seems that its installed in /usr/lib/python2.5/sitepackages Now i have no idea why it got installed there and why it was working earlier and why it stopped working now. Any ideas on how i should fix it. I did try copying the site-packages folder over to the python2.6 folder but that did not work Help!!

    Read the article

  • Trying to build the basic python extension example fails (windows)

    - by Alexandros
    Hello, I have Python 2.6 and Visual Studio 2008 running on a Win7 x64 machine. When I try to build the basic python extension example in c "example_nt" as found in the python 2.6 sources distribution, it fails: python setup.py build And this results in: running build running build_ext building 'aspell' extension Traceback (most recent call last): File "setup.py", line 7, in <module> ext_modules = [module1]) File "C:\Python26\lib\distutils\core.py", line 152, in setup dist.run_commands() File "C:\Python26\lib\distutils\dist.py", line 975, in run_commands self.run_command(cmd) File "C:\Python26\lib\distutils\dist.py", line 995, in run_command cmd_obj.run() File "C:\Python26\lib\distutils\command\build.py", line 134, in run self.run_command(cmd_name) File "C:\Python26\lib\distutils\cmd.py", line 333, in run_command self.distribution.run_command(command) File "C:\Python26\lib\distutils\dist.py", line 995, in run_command cmd_obj.run() File "C:\Python26\lib\distutils\command\build_ext.py", line 343, in run self.build_extensions() File "C:\Python26\lib\distutils\command\build_ext.py", line 469, in build_extensions self.build_extension(ext) File "C:\Python26\lib\distutils\command\build_ext.py", line 534, in build_extension depends=ext.depends) File "C:\Python26\lib\distutils\msvc9compiler.py", line 448, in compile self.initialize() File "C:\Python26\lib\distutils\msvc9compiler.py", line 358, in initialize vc_env = query_vcvarsall(VERSION, plat_spec) File "C:\Python26\lib\distutils\msvc9compiler.py", line 274, in query_vcvarsall raise ValueError(str(list(result.keys()))) ValueError: [u'path'] What can I do to fix this? Any help will be appreciated

    Read the article

  • Emailing smtp with Python error

    - by jakecar
    I can't figure out why this isn't working. I'm trying to send an email from my school email address with this code I got online. The same code works for sending from my GMail address. Does anyone know what this error means? The error occurs after waiting for about one and a half minutes. import smtplib FROMADDR = "FROM_EMAIL" LOGIN = "USERNAME" PASSWORD = "PASSWORD" TOADDRS = ["TO_EMAIL"] SUBJECT = "Test" msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (FROMADDR, ", ".join(TOADDRS), SUBJECT) ) msg += "some text\r\n" server = smtplib.SMTP('OUTGOING_SMTP', 587) server.set_debuglevel(1) server.ehlo() server.starttls() server.login(LOGIN, PASSWORD) server.sendmail(FROMADDR, TOADDRS, msg) server.quit() And here's the error I get: Traceback (most recent call last): File "emailer.py", line 13, in server = smtplib.SMTP('OUTGOING_SMTP', 587) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in init (code, msg) = self.connect(host, port) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 295, in connect self.sock = self._get_socket(host, port, self.timeout) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 273, in _get_socket return socket.create_connection((port, host), timeout) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 514, in create_connection raise error, msg socket.error: [Errno 60] Operation timed out

    Read the article

  • Is there a good way of automatically generating javascript client code from server side python

    - by tat.wright
    I basically want to be able to: Write a few functions in python (with the minimum amount of extra meta data) Turn these functions into a web service (with the minimum of effort / boiler plate) Automatically generate some javascript functions / objects for rpc (this should prevent me from doing as many stupid things as possible like mistyping method names, forgetting the names of methods, passing the wrong number of arguments) Example python: def hello_world(): return "Hello world" javascript: ... <!-- This file is automatically generated (either dynamically or statically) --> <script src="http://myurl.com/webservice/client_side_javascript"> </script> ... <script> $('#button').click(function () { hello_world(function (data){ $('#label').text(data))) } </script> A bit of research has shown me some approaches that come close to this: Automatic generation of json-rpc services from functions with a little boiler plate code in python and then using jquery and json to do the calls (still easy to make mistakes with method names - still need to be aware of urls when calling, very irritating to write these calls yourself in the firebug shell) Using a library like soaplib to generate wsdl from python (by adding copious type information). And then somehow convert this into javascript (not sure if there is even a library to do this) But are there any approaches closer to what I want?

    Read the article

  • android python full integration

    - by Grzegorz Oledzki
    Is there a way to fully integrate Python with Java code on Android platform? Yes, I saw the question about running Python on Android and Android Scripting Environment (ASE). But that doesn't seem to be enough (correct me if I am wrong). I wanted to be able not only to invoke a Python script from within Java code, but have a full integration. The feature I need the most is the ability to have a state of execution of python code saved and be able to run several parts of code on demand against the same execution state. On JavaSE I would rely on Jython. I believe its simplest example shows it all (and some other features too, like something I would call variable state introspection): http://www.jython.org/archive/21/docs/embedding.html PythonInterpreter interp = new PythonInterpreter(); System.out.println("Hello, brave new world"); interp.exec("import sys"); interp.exec("print sys"); interp.set("a", new PyInteger(42)); interp.exec("print a"); interp.exec("x = 2+2"); PyObject x = interp.get("x"); System.out.println("x: "+x); System.out.println("Goodbye, cruel world"); Is it possible on Android? Is ASE a way to go?

    Read the article

  • Gzip and subprocess' stdout in python

    - by pythonic metaphor
    I'm using python 2.6.4 and discovered that I can't use gzip with subprocess the way I might hope. This illustrates the problem: May 17 18:05:36> python Python 2.6.4 (r264:75706, Mar 10 2010, 14:41:19) [GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gzip >>> import subprocess >>> fh = gzip.open("tmp","wb") >>> subprocess.Popen("echo HI", shell=True, stdout=fh).wait() 0 >>> fh.close() >>> [2]+ Stopped python May 17 18:17:49> file tmp tmp: data May 17 18:17:53> less tmp "tmp" may be a binary file. See it anyway? May 17 18:17:58> zcat tmp zcat: tmp: not in gzip format Here's what it looks like inside less HI ^_<8B>^H^Hh<C0><F1>K^B<FF>tmp^@^C^@^@^@^@^@^@^@^@^@ which looks like it put in the stdout as text and then put in an empty gzip file. Indeed, if I remove the "Hi\n", then I get this: May 17 18:22:34> file tmp tmp: gzip compressed data, was "tmp", last modified: Mon May 17 18:17:12 2010, max compression What is going on here?

    Read the article

  • CentOS: make python 2.6 see django

    - by NP
    In a harrowing attempt to get mod_wsgi to run on CentOS 5.4, I've added python 2.6 as an optional library following the instructions here. The configuration seems fine except that when trying to ping the server the Apache log prints this error: mod_wsgi (pid=20033, process='otalo', application='127.0.0.1|'): Loading WSGI script '...django.wsgi'. [Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] mod_wsgi (pid=20033): Target WSGI script '...django.wsgi' cannot be loaded as Python module. [Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] mod_wsgi (pid=20033): Exception occurred processing WSGI script '...django.wsgi'. [Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] Traceback (most recent call last): [Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] File "...django.wsgi", line 8, in [Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] import django.core.handlers.wsgi [Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] ImportError: No module named django.core.handlers.wsgi when I go to my python2.6 install's command line and try 'import django', the module is not found (ImportError). However, my default python 2.4 installation (still working fine) is able to import successfully. How do I point python 2.6 to django? Thanks in advance.

    Read the article

  • Python and Unicode: How everything should be Unicode

    - by A A
    Forgive if this a long a question: I have been programming in Python for around six months. Self taught, starting with the Python tutorial and then SO and then just using Google for stuff. Here is the sad part: No one told me all strings should be Unicode. No, I am not lying or making this up, but where does the tutorial mention it? And most examples also I see just make use of byte strings, instead of Unicode strings. I was just browsing and came across this question on SO, which says how every string in Python should be a Unicode string. This pretty much made me cry! I read that every string in Python 3.0 is Unicode by default, so my questions are for 2.x: Should I do a: print u'Some text' or just print 'Text' ? Everything should be Unicode, does this mean, like say I have a tuple: t = ('First', 'Second'), it should be t = (u'First', u'Second')? I read that I can do a from __future__ import unicode_literals and then every string will be a Unicode string, but should I do this inside a container also? When reading/ writing to a file, I should use the codecs module. Right? Or should I just use the standard way or reading/ writing and encode or decode where required? If I get the string from say raw_input(), should I convert that to Unicode also? What is the common approach to handling all of the above issues in 2.x? The from __future__ import unicode_literals statement? Sorry for being a such a noob, but this changes what I have been doing for a long time and so clearly I am confused.

    Read the article

  • Upload using python script takes very long on one laptop as compared to another

    - by Engr Am
    I have a python 2.7 code which uses STORBINARY function for uploading files to an ftp server and RETRBINARY for downloading from this server. However, the issue is the upload is taking a very long time on three laptops from different brands as compared to a Dell laptop. The strange part is when I manually upload any file, it takes the same time on all the systems. The manual upload rate and upload rate with the python script is the same on the Dell Laptop. However, on every other brand of laptop (I have tried with IBM, Toshiba, Fujitsu-Siemens) the python script has a very low upload rate than the manual attempt. Also, on all these other laptops, the upload rate using the python script is the same (1Mbit/s) while the manual upload rate is approx. 8 Mbit/s. I have tried to vary the filesize for the upload to no avail. TCP Optimizer improved the download rate on all the systems but had no effect on the upload rate. Download rate using this script on all the systems is fine and same as the manual download rate. I have checked the server and it has more than 90% free space. The network connection is the same for all the laptops, and I try uploading only with one laptop at a time. All the laptops have almost the same system configurations, same operating system and approximately the same free drive space. If anything the Dell laptop is a little less in terms of processing power and RAM than 2 of the others, but I suppose this has no effect as I have checked many times to see how much was the CPU usage and network usage during these uploads and downloads, and I am sure that no other virus or program has been eating up my bandwidth. Here is the code ('ftp' and 'file_path' are inputs to the function): path,filename=os.path.split(file_path) filesize=os.path.getsize(file_path) deffilesize=(filesize/1024)/1024 f = open(file_path, "rb") upstart = time.clock() print ftp.storbinary("STOR "+filename, f) upende = time.clock()-upstart outname="Upload " f.close() return upende, deffilesize, outname

    Read the article

  • template files in python

    - by saminny
    I am trying to use python for translating a set of templates to a set of configuration files based on values taken from a main configuration file. However, I am having certain issues. Consider the following example of a template file. file1.cfg.template %(CLIENT1)s %(HOST1)s %(PORT1)d C %(COMPID1)s %(CLIENT2)s %(HOST2)s %(PORT2)d C %(COMPID2)s This file contains an entry for each client. There are hundreds of config files like this and I don't want to have logic for each type of config file. Python should do the replacements and generate config files automatically given a set of global values read from a main xml config file. However, in the above example, if CLIENT2 does not exist, how do I delete that line? I expect Python would generate the config file using the following simple code: os.open("file1.cfg.template").read() & myhash where myhash is hash of all configuration parameters which may not contain CLIENT2 at all. In the case it does not contain CLIENT2, I want that line to disappear from the file. Is it possible to insert some 'IF' block in the file and have python evaluate it? Thanks for your help. Any suggestions most welcome.

    Read the article

  • floating point equality in Python and in general

    - by eric.frederich
    I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly. The following piece of code will print 1.0 == 1.0 -> False But if you replace factors[units_from] with 10.0 and factors[units_to ] with 1.0 / 2.54 it will print 1.0 == 1.0 -> True #!/usr/bin/env python base = 'cm' factors = { 'cm' : 1.0, 'mm' : 10.0, 'm' : 0.01, 'km' : 1.0e-5, 'in' : 1.0 / 2.54, 'ft' : 1.0 / 2.54 / 12.0, 'yd' : 1.0 / 2.54 / 12.0 / 3.0, 'mile' : 1.0 / 2.54 / 12.0 / 5280, 'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12, } # convert 25.4 mm to inches val = 25.4 units_from = 'mm' units_to = 'in' base_value = val / factors[units_from] ret = base_value * factors[units_to ] print ret, '==', 1.0, '->', ret == 1.0 Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it. I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register. Questions What is the best way to avoid problems like this?... In Python or in general. Am I doing something completely wrong? Side Note This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units. Rhetorical Questions If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats Should compilers support an option to replace all float equality checks with a 'close enough' function? Do compilers already do this and I just can't find the information.

    Read the article

  • Python calling class methods with the wrong number of parameters

    - by Hussain
    I'm just beginning to learn python. I wrote an example script to test OOP in python, but something very odd has happened. When I call a class method, Python is calling the function with one more parameter than given. Here is the code: 1. class Bar: 2. num1,num2 = 0,0 3. def __init__(num1,num2): 4. num1,num2 = num1,num2 5. def foo(): 6. if num1 num2: 7. print num1,'is greater than ',num2,'!' 8. elif num1 is num2: 9. print num1,' is equal to ',num2,'!' 10. else: 11. print num1,' is less than ',num2,'!' 12. a,b,t = 42,84,bar(a,b) 13. t.foo 14. 15. t.num1 = t.num1^t.num2 16. t.num2 = t.num2^t.num1 17. t.num1 = t.num1^t.num2 18. 19. t.foo 20. And the error message I get: python test.py Traceback (most recent call last): File "test.py", line 12, in a,b,t = 42,84,bar(a,b) NameError: name 'bar' is not defined Can anyone help? Thanks in advance

    Read the article

  • template files evaluation in python

    - by saminny
    I am trying to use python for translating a set of templates to a set of configuration files based on values taken from a main configuration file. However, I am having certain issues. Consider the following example of a template file. file1.cfg.template %(CLIENT1)s %(HOST1)s %(PORT1)d C %(COMPID1)s %(CLIENT2)s %(HOST2)s %(PORT2)d C %(COMPID2)s This file contains an entry for each client. There are hundreds of config files like this and I don't want to have logic for each type of config file. Python should do the replacements and generate config files automatically given a set of global values read from a main xml config file. However, in the above example, if CLIENT2 does not exist, how do I delete that line? I expect Python would generate the config file using something like this: os.open("file1.cfg.template").read() % myhash where myhash is hash of configuration parameters from the main config file which may not contain CLIENT2 at all. In the case it does not contain CLIENT2, I want that line to disappear from the file. Is it possible to insert some 'IF' block in the file and have python evaluate it? Thanks for your help. Any suggestions most welcome.

    Read the article

  • Secure Copy File from remote server via scp and os module in Python

    - by user1063572
    I'm pretty new to Python and programming. I'm trying to copy a file between two computers via a python script. However the code os.system("ssh " + hostname + " scp " + filepath + " " + user + "@" + localhost + ":" cwd) won't work. I think it needs a password, as descriped in How do I copy a file to a remote server in python using scp or ssh?. I didn't get any error logs, the file just won't show in my current working directory. However every other command with os.system("ssh " + hostname + "command") or os.popen("ssh " + hostname + "command") does work. - command = e.g. ls When I try ssh hostname scp file user@local:directory in the commandline it works without entering a password. I tried to combine os.popen commands with getpass and pxssh module to establish a ssh connection to the remote server and use it to send commands directly (I only tested it for an easy command): import pxssh import getpass ssh = pxssh.pxssh() ssh.force_password = True hostname = raw_input("Hostname: ") user = raw_input("Username: ") password = getpass.getpass("Password: ") ssh.login(hostname, user, password) test = os.popen("hostname") print test But I'm not able to put commands through to the remote server (print test shows, that hostname = local and not the remote server), however I'm sure, the conection is established. I thought it would be easier to establish a connection than always use "ssh " + hostname in the bash commands. I also tried some of the workarounds in How do I copy a file to a remote server in python using scp or ssh?, but I must admit due to lack of expirience I didn't get them to work. Thanks a lot for helping me.

    Read the article

  • Access array of c-structs using Python ctypes

    - by sadris
    I have a C-function that allocates memory at the address passed to and is accessed via Python. The pointer contents does contain an array of structs in the C code, but I am unable to get ctypes to access the array properly beyond the 0th element. How can I get the proper memory offset to be able to access the non-zero elements? Python's ctypes.memset is complaining about TypeErrors if I try to use their ctypes.memset function. typedef struct td_Group { unsigned int group_id; char groupname[256]; char date_created[32]; char date_modified[32]; unsigned int user_modified; unsigned int user_created; } Group; int getGroups(LIBmanager * handler, Group ** unallocatedPointer); ############# python code below: class Group(Structure): _fields_ = [("group_id", c_uint), ("groupname", c_char*256), ("date_created", c_char*32), ("date_modified", c_char*32), ("user_modified", c_uint), ("user_created", c_uint)] myGroups = c_void_p() count = libnativetest.getGroups( nativePointer, byref(myGroups) ) casted = cast( myGroups, POINTER(Group*count) ) for x in range(0,count): theGroup = cast( casted[x], POINTER(Group) ) # this only works for the first entry in the array: print "~~~~~~~~~~" + theGroup.contents.groupname Related: Access c_char_p_Array_256 in Python using ctypes

    Read the article

  • A friend told me Python is garbage, I'm taking web design classes in the Spring and I have a textbook on C++. What should I do? [on hold]

    - by user107165
    I dont know if I should start digging into Python beforehand just to get acquanited with programming and "whet my appetite" or if I should work on the C++ book... Python definitely has more resources around town and I like the beginner friendly approach that seems to go along with every site that appeals to it. Or should I just wait for my assignments that start in 4 months? Any tips for an aspiring programmer?

    Read the article

  • Guidance on E-commerce in a Python Framework

    - by Ant
    I am looking for guidance in making decisions on using Python for E-commerce. My reasoning to use Python in the first place is i do a lot of 3D so it's a real help to use Python for web server side as well as 3D so I do not need to learn a new language. When I say E-commerce i mean the logic behind displaying products and a check out system that is Robust....and yes I really want to build this myself so I can change it. I do not want to use an out the box solution that costs a lot of money every month. I want control of server side, data bases, e-commerce etc. My questions are: What Frameworks are out there? I looked at previous questions on stackoverflow but only found old posts about Sachmo and Get paid. What is the learning path, I do not want to make a mistake that costs six months of studying? Python then Django? How long if I spent 10 hours a day studying this would it take to get up and running? I write javaScript badly, so I am not a complete noob, I understand the basics of programming languages. many thanks in advance

    Read the article

< Previous Page | 40 41 42 43 44 45 46 47 48 49 50 51  | Next Page >