Re: [Tutor] A question about using stdin/out/err vs named files
George R Goffe wrote: > When you run a python program, it appears that stdin, stdout, and stderr > are opened automatically. > > I've been trying to find out how you tell if there's data in stdin (like > when you pipe data to a python program) rather than in a named input file. > It seems like most/all the Unix/Linux commands are able to figure this > out. Do you know how Python programs do this or might do this? I don't think there is a way to guess that. Instead there is an optional commandline argument; if that is missing or '-' the script assumes stdin as the default. With argparse you spell it like this: $ cat upper.py #!/usr/bin/env python3 import argparse import sys parser = argparse.ArgumentParser(description="Convert input to uppercase") parser.add_argument( "input", type=argparse.FileType("r"), default=sys.stdin, nargs="?", help="Input file or '-' for stdin. Default: stdin.") for line in parser.parse_args().input: print(line.upper(), end="") $ ./upper.py Hello HELLO $ ./upper.py upper.py #!/USR/BIN/ENV PYTHON3 IMPORT ARGPARSE IMPORT SYS PARSER = ARGPARSE.ARGUMENTPARSER(DESCRIPTION="CONVERT INPUT TO STDIN") PARSER.ADD_ARGUMENT( "INPUT", TYPE=ARGPARSE.FILETYPE("R"), DEFAULT=SYS.STDIN, NARGS="?", HELP="INPUT FILE OR '-' FOR STDIN. DEFAULT: STDIN.") FOR LINE IN PARSER.PARSE_ARGS().INPUT: PRINT(LINE.UPPER(), END="") There is also the fileinput module. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A question about using stdin/out/err vs named files
On 18/10/14 19:36, George R Goffe wrote: When you run a python program, it appears that stdin, stdout, and stderr are opened automatically. correct. I've been trying to find out how you tell if there's data in stdin Same way you tell if there's data in any file/stream - you read from it. In the old days when I programmed in C there were a pair of calls often used for this: getc() and ungetc(). You read a character with getc() then pout it back with ungetc(). Unfortunately they don't exist in Python stdlib. But, there is a getch()/ungetch() in the msvcrt for Windows, so you could use that. The curses module on linux has an ungetch() but no getch() - which seems bizarre... Steven has posted a solution using read(1) but that blocks so you need to use the isatty() method which all seems a bit messy and doesn't work with tty input. On further investigation the curses.screen object has a getch() method, but its not clear how the curses.ungetch() relates to that (there's no help() documentation) and I've run out of time to experiment. But if you need a linux solution that works with any kind of stdin that might be worth exploring. Sorry, not a great answer but hopefully its of some use. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] python draw christman tree using loops
Dear All, or improve my understanding o python I would like to learn how to draw simple figures using loops. I start from this code in java: import java.util.Scanner; public class Eserc2_8 { public static void main(String args[]) { Scanner s = new Scanner(System.in); // Altezza del triangolo int altezza = s.nextInt(); for (int riga = 1; riga <= altezza; riga++) { int i = 0; while (ihttps://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python draw christman tree using loops
On Sun, Oct 19, 2014 at 7:32 AM, jarod...@libero.it wrote: > > Dear All, > or improve my understanding o python I would like to learn how to draw simple > figures using loops. > I start from this code in java: > import java.util.Scanner; > > public class Eserc2_8 { > public static void main(String args[]) { > Scanner s = new Scanner(System.in); > // Altezza del triangolo > int altezza = s.nextInt(); > > for (int riga = 1; riga <= altezza; riga++) { > int i = 0; > while (i System.out.print(" "); > i += 1; > } > i = 0; > while (i< (riga*2)-1) { > System.out.print("*"); > i += 1; > } > System.out.println(""); > } > } > } > > and I want to transfer to python loops: > > for i in range(10): > #space > for t in range(6-i): > print "" > for item in range(i+1): > print "." > > > But I ha not succed. So someone could you please explain how can work' > thanks a lot > bw > what is your output? What errors (print complete traceback) You probably want print " ", and print ".", so that there is no added newline. > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A question about using stdin/out/err vs named files
* Peter Otten <__pete...@web.de> [2014-10-19 10:05]: > George R Goffe wrote: > > > When you run a python program, it appears that stdin, stdout, and stderr > > are opened automatically. > > > > I've been trying to find out how you tell if there's data in stdin (like > > when you pipe data to a python program) rather than in a named input file. > > It seems like most/all the Unix/Linux commands are able to figure this > > out. Do you know how Python programs do this or might do this? > > There is also the fileinput module. I use fileinput all the time. "This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed." It gives a fairly clean way to just "do the Right Thing" whether you are feeding files, or reading from stdin. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] A question about using stdin/out/err vs named files
Hi, Wow. Lots of feedback. REALLY GOOD FEEDBACK! This was my first question to this list. Let me clarify my question. I want to use tst.py as follows: tst.py input-file output-file OR cat data-file | tst.py - output-file OR cat data-file | tst.py output-file tst.py input-file output-file works well tst.py - output-file works well The question boils down to "tst.py output-file"... which is a "parsing the args" question which you "guys" have caused me to think more clearly about. If there's just 1 arg, consider it an output-file and read from stdin and write to output-file ONLY if output-file does not exist. Thank you all for your very helpful and informative responses. Regards, George... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python draw christman tree using loops
On Sun, Oct 19, 2014 at 9:27 AM, jarod...@libero.it wrote: > thanks for the help: > In [60]: for i in range(10): >: for t in range(6-i): >: print " " >: for item in range(i+1): >: print "*" >: > > * > > * > > * > > * > > * > > * > > * > * > > * > * > > * > * > > * > * > > * > * > > * > * > * > > * > * > * > > * > * > * > > * > * > * > > * > * > * > * > > * > * > * > * > > * > * > * > * > > * > * > * > * > * > > * > * > * > * > * > > * > * > * > * > * > * > > this i the output.. it is not a tree.. > > >>Messaggio originale >>Da: joel.goldst...@gmail.com >>Data: 19/10/2014 14.10 >>A: "jarod...@libero.it" >>Cc: , "tutor@python.org" >>Ogg: Re: [Tutor] python draw christman tree using loops >> >>On Sun, Oct 19, 2014 at 7:32 AM, jarod...@libero.it > wrote: >>> >>> Dear All, >>> or improve my understanding o python I would like to learn how to draw > simple >>> figures using loops. >>> I start from this code in java: >>> import java.util.Scanner; >>> >>> public class Eserc2_8 { >>> public static void main(String args[]) { >>> Scanner s = new Scanner(System.in); >>> // Altezza del triangolo >>> int altezza = s.nextInt(); >>> >>> for (int riga = 1; riga <= altezza; riga++) { >>> int i = 0; >>> while (i>> System.out.print(" "); >>> i += 1; >>> } >>> i = 0; >>> while (i< (riga*2)-1) { >>> System.out.print("*"); >>> i += 1; >>> } >>> System.out.println(""); >>> } >>> } >>> } >>> >>> and I want to transfer to python loops: >>> >>> for i in range(10): >>> #space >>> for t in range(6-i): >>> print "" >>> for item in range(i+1): >>> print "." >>> >>> >>> But I ha not succed. So someone could you please explain how can work' >>> thanks a lot >>> bw >>> >>what is your output? What errors (print complete traceback) >> >>You probably want print " ", and print ".", so that there is no added > newline. >>> In python 2.x you can add a comma to the print statement so that it will not generate a newline. That way your *s will print across. After you loop use plain print to go to next line. Also, reply to the list, not to me. >>> >>> ___ >>> Tutor maillist - Tutor@python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >> >> >> >>-- >>Joel Goldstick >>http://joelgoldstick.com >> > > -- Joel Goldstick http://joelgoldstick.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python draw christman tree using loops
In Java, System.out represents the standard output device. In Python, there's a similar value in sys.stdout. https://docs.python.org/2/library/sys.html#sys.stdout In your Python program, you should be able to say: import sys at the beginning of your program, and then use: sys.stdout.write(" ") and: sys.stdout.write("*") with the expected results. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Need help to convert pdf to excel
Hell, My name is Amna and I am totally new to python world with zero experience in programming. I am facing the challenge of converting data from pdf to excel. The data within pdf is numbers separated by space not within a table. I need a help to figure out a code that help me to convert these pdf to excel. How can I do that. Thank you, Amna ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A question about using stdin/out/err vs named files
On 10/18/2014 02:36 PM, George R Goffe wrote: > Hi, > > When you run a python program, it appears that stdin, stdout, and stderr are > opened automatically. > > I've been trying to find out how you tell if there's data in stdin (like when > you pipe data to a python program) rather > than in a named input file. It seems like most/all the Unix/Linux > commands are able to figure this out. Do you know how Python programs do this > or might do this? > > MANY thanks for any/all help/hints/tips/suggestions, > > George... Command line argument parsing aside, perhaps something like this would be useful: script.py --- #!/usr/bin/env python3 import os, stat mode = os.fstat(0).st_mode if stat.S_ISFIFO(mode): print("stdin is a pipe") elif stat.S_ISREG(mode): print("stdin is a redirected file") elif stat.S_ISCHR(mode): print("stdin is terminal") else: print("stdin is weird") --- $ ./script.py stdin is terminal $ cat script.py | ./script.py stdin is a pipe $ ./script.py < script.py stdin is a redirected file ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help to convert pdf to excel
On Sun, Oct 19, 2014 at 7:27 AM, AMNA MOHAMMED ALRUHEILI wrote: > My name is Amna and I am totally new to python world with zero experience in > programming. I am facing the challenge of converting data from pdf to excel. > The data within pdf is numbers separated by space not within a table. > I need a help to figure out a code that help me to convert these pdf to > excel. Can you get the original data in a format that is not PDF? PDF is a human-centric published format: its concerns are typographic. It is not intended primarily for computers to extract data. Certainly you can extract data from it, but it won't be structured in a way that makes it particularly easy. That being said: you might try an approach that gets text from a PDF: http://stackoverflow.com/questions/25665/python-module-for-converting-pdf-to-text and then write some processing program that takes that text and inserts into an excel spreadsheet. There are several libraries that other programmers have written to write Excel documents from Python. For example: https://xlsxwriter.readthedocs.org/ As a side comment: this task actually does require a significant bit of programming knowledge. I believe it would be an unfair and unreasonable request to ask a complete programming beginner to do this without some basic programming training. I would strongly recommend taking an introductory programming class first, before trying to tackle your PDF->Excel problem head on. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] what am I not understanding?
raw_table = (''' a: Asky: Dividend Yield b: Bid d: Dividend per Share b2: Ask (Realtime) r1: Dividend Pay Date b3: Bid (Realtime)q: Ex-Dividend Date p: Previous Close o: Open''') key_name = raw_table.rstrip('\t') print(key_name) a: Asky: Dividend Yield b: Bid d: Dividend per Share b2: Ask (Realtime) r1: Dividend Pay Date b3: Bid (Realtime)q: Ex-Dividend Date p: Previous Close o: Open#why is the tab not being removed? key_name = raw_table.rstrip('\n') print(key_name) a: Asky: Dividend Yield b: Bid d: Dividend per Share b2: Ask (Realtime) r1: Dividend Pay Date b3: Bid (Realtime)q: Ex-Dividend Date p: Previous Close o: Open# why is the \n not being removed? key_name = raw_table.split('\t') print(key_name) ['\na: Ask', 'y: Dividend Yield\nb: Bid', 'd: Dividend per Share\nb2: Ask (Realtime)', 'r1: Dividend Pay Date\nb3: Bid (Realtime)'. #great the tab is being removed but now I have to remove the \n but it is no longer a string key_name = raw_table.split('\n') print(key_name) ['', 'a: Ask\ty: Dividend Yield', 'b: Bid\td: Dividend per Share', 'b2: Ask (Realtime)\tr1: Dividend Pay Date', 'b3: Bid (Realtime)\tq: Ex-Dividend Date'. #great, the \n is being "removed" but now I have to remove the \t, but it is no longer a string key_name = raw_table.split('\t\n') print(key_name) ['\na: Ask\ty: Dividend Yield\nb: Bid\td: Dividend per Share\nb2: Ask (Realtime)\tr1: Dividend Pay Date\nb3: Bid (Realtime)\tq: Ex-Dividend Date\n. #why isn't the \t and \n not both "removed" key_name = raw_table.rstrip('[\t\n]') a: Asky: Dividend Yield b: Bid d: Dividend per Share b2: Ask (Realtime) r1: Dividend Pay Date b3: Bid (Realtime)q: Ex-Dividend Date p: Previous Close o: Open#why aren't both the \t and \n being removed? (tried with and without the square brackets) I am trying to get to where I can create a dict using the ':' separator Thanks Clayton ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] what am I not understanding?
On 19/10/14 23:26, Clayton Kirkwood wrote: raw_table = (''' a: Asky: Dividend Yield b: Bid d: Dividend per Share b2: Ask (Realtime) r1: Dividend Pay Date ... o: Open’’’) key_name = raw_table.rstrip('\t') rstrip() strips characters from the *right* hand side. When it finds a character that is not a strippable character(the n of Open in this case) it stops. If you want to replace all tabs with spaces or nulls then you need to use string.replace() (or sub for regex) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] what am I not understanding?
On Sun, Oct 19, 2014 at 03:26:44PM -0700, Clayton Kirkwood wrote: > raw_table = (''' > a: Asky: Dividend Yield [...] > o: Open''') > key_name = raw_table.rstrip('\t') > print(key_name) [...] > #why is the tab not being removed? How do you know that the raw_table contains tabs rather than spaces? As far as I can see, it contains spaces, although that might just be an artifact of copying and pasting text into your email. You think you have a problem with tabs not being removed, but it seems to me that your *actual* problem is that you're not really sure whether there are tabs in the string in the first place! Just because you press the TAB key on your keyboard doesn't mean that a tab is inserted. Your system might be confirgured to insert a number of spaces instead. Your editor might automatically convert the tab into spaces. Who knows? Instead of typing TAB, the best way to get tabs into a Python string is to use the \t (backslash-t) escape code. And the best way to see that they are inside a string is to print the repr() of the string: py> raw = "some text " py> print raw # Looks like a leading tab, trailing tab is invisible. some text py> print repr(raw) # But repr() reveals the truth, no tabs here! 'some text ' py> raw = "\tsome text\t" # Actually are tabs. py> print raw some text py> print repr(raw) '\tsome text\t' So the first thing for you to do is to satisfy yourself that what you think are tabs actually are tabs. Then, the second thing is to understand what the rstrip() method actually does. It only removes characters from the right hand end of the string, not everywhere in the string: py> raw = "--some-text" py> print raw.rstrip("-") --some-text (There is also a lstrip() to do only the left hand end of the string, and a strip() method to do both.) "Right hand end" doesn't mean the right hand end of *each line*, only of the entire string: py> raw = """---some-text ... --more--text--- ... -and-even-more--text-""" py> print raw.rstrip("-") ---some-text --more--text--- -and-even-more--text If you want to strip something from the end of each line, first you have to break the string up into individual lines, strip each one, then put them back together again: py> lines = raw.split('\n') py> lines = [line.rstrip('-') for line in lines] py> print '\n'.join(lines) ---some-text --more--text -and-even-more--text To remove from the middle of the string, use the replace() method: py> print raw.replace("-", "") sometext moretext andevenmoretext > key_name = raw_table.split('\t') > print(key_name) [...] > #great the tab is being removed but now I > have to remove the \n but it is no longer a string Right. The split() method isn't a "remove" method, that's why it's called "split" and not "remove". It splits the string into pieces, and returns a list of substrings. You can always join the pieces back together, if you want, or find a better way to remove things. > key_name = raw_table.split('\t\n') > print(key_name) [...] > #why isn't the \t and \n not both "removed" Because you didn't tell Python to remove \t and \n separately. You told it to split the string everywhere it sees the pair of characters \t\n. The argument to split is not a list of individual characters to split on, but an exact substring to split on. If it doesn't match that substring exactly, it won't split and you'll only get one piece: py> print raw ---some-text --more--text--- -and-even-more--text- py> raw.split('ex') ['---some-t', 't\n--more--t', 't---\n-and-even-more--t', 't-'] py> raw.split('xe') ['---some-text\n--more--text---\n-and-even-more--text-'] > I am trying to get to where I can create a dict using the ':' separator It takes about three steps (excluding print statements, which I have only included so you can see the individual steps in action): # Step 1: split the string into "key:value" substrings. py> raw = "a : something, b: another thing, c:yet a third thing" py> items = [s.strip() for s in raw.split(',')] py> print items ['a : something', 'b: another thing', 'c:yet a third thing'] # Step 2: split each substring into a separate (key, value) tuple, # cleaning up any whitespace around them. py> items = [s.split(':') for s in items] py> print items [['a ', ' something'], ['b', ' another thing'], ['c', 'yet a third thing']] py> items = [(key.strip(), value.strip()) for key,value in items] py> print items [('a', 'something'), ('b', 'another thing'), ('c', 'yet a third thing')] # Step 3: convert into a dict. py> d = dict(items) py> print d {'a': 'something', 'c': 'yet a third thing', 'b': 'another thing'} -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor