Search Results

Search found 19539 results on 782 pages for 'pretty print'.

Page 58/782 | < Previous Page | 54 55 56 57 58 59 60 61 62 63 64 65  | Next Page >

  • How to convert raw_input() into a directory?

    - by Azeworai
    Hi everyone, I just picked up IronPython and I've been trying to get this IronPython script going but I'm stuck at trying to get a Path input from raw_input to be a directory path. The first block of code is the broken one that I'm working on. import System from System import * from System.IO import * from System.Diagnostics import * inputDirectory = raw_input("Enter Input Directory's full path [eg. c:\\vid\\]: ") print ("In: "+inputDirectory) outputDirectory = inputDirectory +"ipod\\" print ("Out: "+outputDirectory) #create the default output directory for s in DirectoryInfo(inputDirectory).GetFiles("*.avi"): print s.FullName arg = String.Format('-i "{0}" -t 1 -c 1 -o "{1}" --preset="iPod"' , s.FullName, outputDirectory + s.Name.Replace(".avi", ".mp4")) print arg proc = Process.Start("C:\\Program Files\\Handbrake\\HandBrakeCLI.exe", arg) #path to handbrake goes here proc.WaitForExit() The following code block is what I have working at the moment. import System from System import * from System.IO import * from System.Diagnostics import * for s in DirectoryInfo("F:\\Tomorrow\\").GetFiles("*.avi"): arg = String.Format('-i "{0}" -t 1 -c 1 -o "{1}" --preset="iPod"' , s.FullName, "F:\\Tomorrow\\ipod\\" + s.Name.Replace(".avi", ".mp4")) print arg proc = Process.Start("C:\\Program Files\\Handbrake\\HandBrakeCLI.exe", arg) #path to handbrake goes here proc.WaitForExit() PS: Credit for the above working code goes to Joseph at jcooney.net

    Read the article

  • How do I find out if the variable is declared in Python?

    - by golergka
    I want to use a module as a singleton referenced in other modules. It looks something like this (that's not actually a code I'm working on, but I simplified it to throw away all unrelated stuff): main.py import singleton import printer def main(): singleton.Init(1,2) printer.Print() if __name__ == '__main__': pass singleton.py variable1 = '' variable2 = '' def Init(var1, var2) variable1 = var1 variable2 = var2 printer.py import singleton def Print() print singleton.variable1 print singleton.variable2 I expect to get output 1/2, but instead get empty space. I understand that after I imported singleton to the print.py module the variables got initialized again. So I think that I must check if they were intialized before in singleton.py: if not (variable1): variable1 = '' if not (variable2) variable2 = '' But I don't know how to do that. Or there is a better way to use singleton modules in python that I'm not aware of :)

    Read the article

  • log the http response codes in the file

    - by dexter
    i have created HTTP::Request which looks like this: #!/usr/bin/perl require HTTP::Request; require LWP::UserAgent; require HTTP::Cookies; $request = HTTP::Request->new(GET => 'http://www.google.com/'); $ua = LWP::UserAgent->new; $cookie_jar = HTTP::Cookies->new(); $ua->cookie_jar($cookie_jar); $cookie_jar->set_cookie(0,'testCookie','cookieValue','/','http://www.google.com/',80,0,0,86400,0); $response = $ua->request($request); if($response->is_success){ print "sucess\n"; print $response->code; print "\n"; } else { print "fail\n"; die $response->code; print "\n"; } now, When i send Request: i want to log the http response codes in the file please help thank you

    Read the article

  • Error while trying to parse a website url using python . how to debug it ?

    - by mekasperasky
    #!/usr/bin/python import json import urllib from BeautifulSoup import BeautifulSoup from BeautifulSoup import BeautifulStoneSoup import BeautifulSoup def showsome(searchfor): query = urllib.urlencode({'q': searchfor}) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query search_response = urllib.urlopen(url) search_results = search_response.read() results = json.loads(search_results) data = results['responseData'] print 'Total results: %s' % data['cursor']['estimatedResultCount'] hits = data['results'] print 'Top %d hits:' % len(hits) for h in hits: print ' ', h['url'] resp = urllib.urlopen(h['url']) res = resp.read() soup = BeautifulSoup(res) print soup.prettify() print 'For more results, see %s' % data['cursor']['moreResultsUrl'] showsome('sachin') What is the wrong in this code ? Note all the 4 links that I am getting out of the search , I am feeding it back to extract the contents out of it , and then use BeautifulSoup to parse it . How should I go about it ?

    Read the article

  • crashing out in a while loop python

    - by Edward
    How to solve this error? i want to pass the values from get_robotxya() and get_ballxya() and use it in a loop but it seems that it will crash after awhile how do i fix this? i want to get the values whithout it crashing out of the while loop import socket import os,sys import time from threading import Thread HOST = '59.191.193.59' PORT = 5555 COORDINATES = [] def connect(): globals()['client_socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((HOST,PORT)) def update_coordinates(): connect() screen_width = 0 screen_height = 0 while True: try: client_socket.send("loc\n") data = client_socket.recv(8192) except: connect(); continue; globals()['COORDINATES'] = data.split() if(not(COORDINATES[-1] == "eom" and COORDINATES[0] == "start")): continue if (screen_width != int(COORDINATES[2])): screen_width = int(COORDINATES[2]) screen_height = int(COORDINATES[3]) return def get_ballxy(): update_coordinates() ballx = int(COORDINATES[8]) bally = int(COORDINATES[9]) return ballx,bally def get_robotxya(): update_coordinates() robotx = int(COORDINATES[12]) roboty = int(COORDINATES[13]) angle = int(COORDINATES[14]) return robotx,roboty,angle def print_ballxy(bx,by): print bx print by def print_robotxya(rx,ry,a): print rx print ry print a def activate(): bx,by = get_ballxy() rx,ry,a = get_robotxya() print_ballxy(bx,by) print_robotxya(rx,ry,a) Thread(target=update_coordinates).start() while True: activate() this is the error i get:

    Read the article

  • Why it's not "if" and not "else"?

    - by Roman
    I have this code: $link = mysql_connect("localhost", "ctmanager", "pswsafgcsadfgG"); if ( ! $link ) die("I cannot connect to MySQL.<br>\n"); else print "Connection is established.<br>\n"; print "a"; if ( mysql_create_db("ct", $link) ) print "AAA"; else print "BBB"; print "2"; die(); And this is the output: Connection is established. a So, I cannot understand how it's possible that neither "AAA" no "BBB" is outputted. Is it because program dies at mysql_create_db?

    Read the article

  • Python try/except: Showing the cause of the error after displaying my variables

    - by NealWalters
    I'm not even sure what the right words are to search for. I want to display parts of the error object in an except block (similar to the err object in VBScript, which has Err.Number and Err.Description). For example, I want to show the values of my variables, then show the exact error. Clearly, I am causing a divided-by-zero error below, but how can I print that fact? try: x = 0 y = 1 z = y / x z = z + 1 print "z=%d" % (z) except: print "Values at Exception: x=%d y=%d " % (x,y) print "The error was on line ..." print "The reason for the error was ..."

    Read the article

  • Sending http headers with python

    - by Niklas R
    I've set up a little script that should feed a client with html. import socket sock = socket.socket() sock.bind(('', 8080)) sock.listen(5) client, adress = sock.accept() print "Incoming:", adress print client.recv(1024) print client.send("Content-Type: text/html\n\n") client.send('<html><body></body></html>') print "Answering ..." print "Finished." import os os.system("pause") But it is shown as plain text in the browser. Can you please tell what I need to do ? I just can't find something in google that helps me.. Thanks.

    Read the article

  • Is it possible to have Ant print out the classpath for a particular target? If so, how?

    - by Daryl Spitzer
    I'm trying to get a target to build that has quite a long list of <pathelement location="${xxx}"/> and <path refid="foo.class.path"/> elements in its <path id="bar.class.path"> element (in the build.xml file). I keep getting "package com.somecompany.somepackage does not exist" errors, and I'm having a hard time chasing down these packages and making sure I've synced them from our repository. I'm new to this team so I'm unfamiliar with the build, but I would prefer to figure this out myself if possible (so I don't bother the other very busy team members). I have very limited experience with Ant. I think it would save me quite a bit of time if I could have Ant print out the classpath for the target I'm trying to build.

    Read the article

  • numpy array C api

    - by wiso
    I have a C++ function returning a std::vector and I want to use it in python, so I'm using the C numpy api: static PyObject * py_integrate(PyObject *self, PyObject *args){ ... std::vector<double> integral; cpp_function(integral); // this change integral npy_intp size = {integral.size()}; PyObject *out = PyArray_SimpleNewFromData(1, &size, NPY_DOUBLE, &(integral[0])); return out; } when I call it from python, if I do import matplotlib.pyplot as plt a = py_integrate(parameters) print a fig = plt.figure() ax = fig.add_subplot(111) ax.plot(a) print a the first print is ok, the values are correct, but when I plot a they are not, and in particular in the second print I see very strange values like 1E-308 1E-308 ... or 0 0 0 ... as an unitialized memory. I don't understand why the first print is ok.

    Read the article

  • shell scripting: nested subshell ++

    - by jhon
    Hi guys, more than a problem, this is a request for "another way to do this" actually, if a want to use the result from a previous command I into another one, I use: R1=$("cat somefile | awk '{ print $1 }'" ) myScript -c $R1 -h123 then, a "better way"is: myScript -c $("cat somefile | awk '{ print $1 }'" ) -h123 but, what if I have to use several times the result, let's say: using several times $R1, well the 2 options: option 1 R1=$("cat somefile | awk '{ print $1}'") myScript -c $R1 -h123 -x$R1 option 2 myScript -c $("cat somefile | awk '{ print $1 }'" ) -h123 -x $("cat somefile | awk '{ print $1 }'" ) do you know another way to "store" the result of a previous command/script and use it as a argument into another command/script? thanks

    Read the article

  • Does CLOS have an eql specialization dispatch on strings?

    - by mhb
    Examples of what you can do. (defmethod some-fn ((num real)) (print "an integer")) (defmethod some-fn ((num real)) (print "a real")) (defmethod some-fn ((num (eql 0))) (print "zero")) (some-fn 19323923198319) "an integer" (some-fn 19323923198319.3) "a real" (some-fn 0) "zero" It also works with a general 'string type. (defmethod some-fn ((num string)) (print "a string")) (some-fn "asrt") "a string" Not with a specific string, however (defmethod some-fn ((num (eql "A")) (print "a specifict string"))) => doesn't compile I imagine it doesn't work because eql does not work on strings in the way that would be necessary for it to work. (eql "a" "a") => nil Is there a way to do it?

    Read the article

  • Confused by this PHP Exception try..catch nesting

    - by Domenic
    Hello. I'm confused by the following code: class MyException extends Exception {} class AnotherException extends MyException {} class Foo { public function something() { print "throwing AnotherException\n"; throw new AnotherException(); } public function somethingElse() { print "throwing MyException\n"; throw new MyException(); } } $a = new Foo(); try { try { $a->something(); } catch(AnotherException $e) { print "caught AnotherException\n"; $a->somethingElse(); } catch(MyException $e) { print "caught MyException\n"; } } catch(Exception $e) { print "caught Exception\n"; } I would expect this to output: throwing AnotherException caught AnotherException throwing MyException caught MyException But instead it outputs: throwing AnotherException caught AnotherException throwing MyException caught Exception Could anyone explain why it "skips over" catch(MyException $e) ? Thanks.

    Read the article

  • Why are closures broken within exec?

    - by Devin Jeanpierre
    In Python 2.6, >>> exec "print (lambda: a)()" in dict(a=2), {} 2 >>> exec "print (lambda: a)()" in globals(), {'a': 2} Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1, in <lambda> NameError: global name 'a' is not defined >>> exec "print (lambda: a).__closure__" in globals(), {'a': 2} None I expected it to print 2 twice, and then print a tuple with a single cell. It is the same situation in 3.1. What's going on?

    Read the article

  • printing using one '\n'

    - by Alex
    I am pretty sure all of you are familiar with the concept of the Big4, and I have several stuffs to do print in each of the constructor, assignment, destructor, and copy constructor. The restriction is this: I CAN'T use more than one newline (e.g., ƒn or std::endl) in any method I can have a method called print, so I am guessing print is where I will put that precious one and only '\n', my problem is that how can the method print which prints different things on each of the element I want to print in each of the Big4? Any idea? Maybe overloading the Big4?

    Read the article

  • Python interpreter invocation with "-c" and indentation issues

    - by alexander
    I'm trying to invoke Python using the "-c" argument to allow me to run some arbitrary python code easily, like this: python.exe -c "for idx in range(10): print idx" Now this code works fine, from within my batch file, however, I'm running into problems when I want to do anything more than this. Consider the following Python code: foo = 'bar' for idx in range(10): print idx this would then give you 0-9 on the stdout. However, if I collapse this into a single line, using semicolons as delimiters, to get the following: foo = 'bar';for idx in range(10): print idx and try to run it using python.exe -c it get a SyntaxError raised: C:\Python>python.exe -c "foo = 'bar';for idx in range(10): print idx" File "<string>", line 1 foo = 'bar';for idx in range(10): print idx ^ SyntaxError: invalid syntax Anyone know how I can actually use this without switching to a separate .py file?

    Read the article

  • Python IPC, popen too slow

    - by UnableToLoad
    i need to run a subprocess (./myProgram) form python script and get output, actually i do this: import subprocess proc = subprocess.Popen('./generate_out', shell=False, stdout=subprocess.PIPE, ) while proc.poll() is None: out = proc.stdout.readline() data = doStuff(out) print(data) but is slow, sometimes pass a lot of time between the output produced by ./generate_out and the print(data), knowing that my doStuff() function is very fast, i think there is some buffer slowing down my pipe... Notes: ./generate_out, generates potentially an unlimited number of lines of finite length each. It seems that when too few chars are put in the pipe between the two processes nothing happens, then when enough is produced i get a huge print (non the expected behaviour!) sometimes i wait many seconds (10-20 and more) between generate_out print and python print) what can i do? maybe communicate() is faster? anithing else? Thank you a lot!

    Read the article

  • Regular expressions in python unicode

    - by Remy
    I need to remove all the html tags from a given webpage data. I tried this using regular expressions: import urllib2 import re page = urllib2.urlopen("http://www.frugalrules.com") from bs4 import BeautifulSoup, NavigableString, Comment soup = BeautifulSoup(page) link = soup.find('link', type='application/rss+xml') print link['href'] rss = urllib2.urlopen(link['href']).read() souprss = BeautifulSoup(rss) description_tag = souprss.find_all('description') content_tag = souprss.find_all('content:encoded') print re.sub('<[^>]*>', '', content_tag) But the syntax of the re.sub is: re.sub(pattern, repl, string, count=0) So, I modified the code as (instead of the print statement above): for row in content_tag: print re.sub(ur"<[^>]*>",'',row,re.UNICODE But it gives the following error: Traceback (most recent call last): File "C:\beautifulsoup4-4.3.2\collocation.py", line 20, in <module> print re.sub(ur"<[^>]*>",'',row,re.UNICODE) File "C:\Python27\lib\re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or buffer What am I doing wrong?

    Read the article

  • HTML javascript form submitted when image input button

    - by DreamU
    I have a form that contains this single input field, which is nothing more than a button to Print the current web page: <div align="center"> <input type="image" src="../Images/print.jpg" value="Print" onclick="printpage();" /></div> </div> After the printing, the page re-submits itself (to itself). Why does it do this and can I stop it? If I just change the type to "input", this code does not re-submit itself after printing: <div align="center"> <input type="input" src="../Images/print.jpg" value="Print" onclick="printpage();" /></div> </div> Unfortunately, our style conventions require me to use that button image rather than the standard input button.

    Read the article

  • Java static method parameters

    - by Blitzkr1eg
    Why does the following code return 100 100 1 1 1 and not 100 1 1 1 1 ? public class Hotel { private int roomNr; public Hotel(int roomNr) { this.roomNr = roomNr; } public int getRoomNr() { return this.roomNr; } static Hotel doStuff(Hotel hotel) { hotel = new Hotel(1); return hotel; } public static void main(String args[]) { Hotel h1 = new Hotel(100); System.out.print(h1.getRoomNr() + " "); Hotel h2 = doStuff(h1); System.out.print(h1.getRoomNr() + " "); System.out.print(h2.getRoomNr() + " "); h1 = doStuff(h2); System.out.print(h1.getRoomNr() + " "); System.out.print(h2.getRoomNr() + " "); } } Why does it appear to pass Hotel by-value to doStuff() ?

    Read the article

  • Perl, Array called by scalar doesn't work in foreach loop.

    - by foxhop
    This code outputs the scalars in the row array properly: $line = "This is my favorite test"; @row = split(/ /, $line); print $row[0]; print $row[1]; The same code inside a foreach loop doesn't print any scalar values: foreach $line (@lines){ @row = split(/ /, $line); print $row[0]; print $row[1]; } What could cause this to happen? I am new to perl coming from python. I need to learn perl for my new position.

    Read the article

  • Adding a decorator that converts strings to lowercase in Python

    - by user2905382
    So I am new to learning decorators and I have gone through countless tutorials and while I understand and can mostly follow all of the examples, I think the best way to learn, would be to implement a decorator myself. So I am going to use this example below. I realize a decorator is not at all necessary to do this, but for the sake of learning, I would like to add a decorator that filters the strings like dog name and breed and turns them into lowercase. Any ideas or pointers in the right direction would be appreciated. class Dogs: totalDogs = 0 dogList=[] def __init__(self, breed, color, age): self.breed=breed self.color=color self.age=age Dogs.dogList.append(self.breed) Dogs.totalDogs += 1 def displayDogs(self): print "breed: ", self.breed print "color: ",self.color print "age: ",self.age print "list of breeds:", Dogs.dogList print "total dogs: ", Dogs.totalDogs def somedecorator(*args): #now what terrier=Dogs("TeRrIer", "white", 5) terrier.displayDogs() retriever=Dogs("goldenRETRIEVER", "brown", 10) retriever.displayDogs()

    Read the article

  • How to read piped input in Perl?

    - by Jenni
    I am trying to create something in Perl that is basically like the Unix "tee" command. I'm trying to read each line of STDIN, run a substitution on it, and print it. (And eventually, also print it to a file.) This works if I'm using console input, but if I try to pipe input to the command it doesn't do anything. Here's a simple example: print "about to loop\n"; while(<STDIN>) { s/2010/2009/; print; } print "done!\n"; I try to pipe the dir command to it like this: C:\perltestdir | mytee.pl about to loop done! Why is it not seeing the piped input?

    Read the article

  • sqlite & python - only pulls the first result

    - by pencilNero
    This is pretty strange (admitedly, this is my first attempt with python / sqlite), but I can seem to get all of the rows if I do a fetchAll(), but other than that - no matter what I try, always ends up in the db only returning the first row - the second iteration stops because a null is returned. Wondering if there is something wrong with how I am coding this up in python? The db seems ok.. con = sqlite3.connect('backup.db') con.row_factory = sqlite3.Row cur = con.cursor() cur.execute('select * from tb1;') for row in cur: try: # row = dataCur.fetchone() #if row == None: break print type(row) print ' Starting on: %i' % row[0] cleaner = Cleaner(scripts=True, remove_tags=['img'], embedded=True) try: cleaned = cleaner.clean_html(row[2]) #data stored in second col cur.execute('update tb1 set data = ? where id = ?;', (cleaned, row[0])) except AttributeError: print 'Attribute error' print ' Ended on: %i' % row[0] except IOError: print 'IOexception'

    Read the article

  • Drupal 6: pre-defined variable for amount [count] of custom type items...

    - by artmania
    Hi friends, I'm a drupal newbie... I researched but couldnot find :/ is there any predefined variable that gives my CCK field value count? for example; I have field_logo_sponsor and I need to display all logo items. Now I have 5 item <?php print $node->field_logo_sponsor[0]['view'] ?> <?php print $node->field_logo_sponsor[1]['view'] ?> <?php print $node->field_logo_sponsor[2]['view'] ?> <?php print $node->field_logo_sponsor[3]['view'] ?> <?php print $node->field_logo_sponsor[4]['view'] ?> it is stupid to use it that way :/ if there is any count variable for that, I will just create a loop for that and display them in a for or while loop Appreciate helps! thanks a lot!

    Read the article

< Previous Page | 54 55 56 57 58 59 60 61 62 63 64 65  | Next Page >