PDA

View Full Version : Anyone familiar/proficient with Python?


dudewithasock
2007-07-22, 02:12 AM
Hi all,

I've decided I wanted to try my hand at programming a little bit, and I've chosen to learn the Python language, mainly because Blender3D utilizes it for the game engine and certain rendering plugins. I just want to know if there's anyone on here that I could PM at any time and ask for some help if I get stuck on a certain concept. I don't actually have a question right now (though any general advice would be well-appreciated), I'd just like to know if there's anyone on the forums I could turn to should one arise.

Thanks!
-Matt

Brian O.
2007-07-22, 02:51 AM
I'm no expert with it but I do know it.

dudewithasock
2007-07-22, 03:03 AM
Alright, thanks for the reply Brian. I'm currently using this tutorial (http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python), and after I finish I'll probably try my hand at my own very basic program, and I hope you don't mind if I ask for any help along the way. :)

mark williamson
2007-07-22, 03:03 AM
Yah, I've worked with it a fair bit. Not to say that my code is as neat / simple as a python whiz could do ;) but I have done some moderately complex things with it.

Hi all,

I've decided I wanted to try my hand at programming a little bit, and I've chosen to learn the Python language, mainly because Blender3D utilizes it for the game engine and certain rendering plugins. I just want to know if there's anyone on here that I could PM at any time and ask for some help if I get stuck on a certain concept. I don't actually have a question right now (though any general advice would be well-appreciated), I'd just like to know if there's anyone on the forums I could turn to should one arise.

Thanks!
-Matt

dudewithasock
2007-07-22, 03:50 AM
Alright I already have a question...IDLE keeps not opening for me...says it can't complete a subprocess or something, won't let me run anything in idle. How do I run a program in python using the command line?

burjzyntski
2007-07-22, 04:49 PM
Evilnick is our resident *nix guru; I'd ask him if I were you.

Python is not exactly my language of choice, but I do know a bit about it. Feel free to PM me if you ever need help with C+/++ or Java, though.

EDIT: Download TextPad (http://www.textpad.com/). It ought to help you out a bit. I prefer it over other IDEs.

leo
2007-07-22, 05:56 PM
EDIT: Download TextPad (http://www.textpad.com/). It ought to help you out a bit. I prefer it over other IDEs.
I only see .exe's available. What about vim on your unixshell, does indenting and coloring to (still I use pico, ee and very sometimes vi).

john_childs
2007-07-23, 10:15 PM
I'm curious if you're doing Python on Windows or if you're using Linux?

Python has been on my todo list to learn or investigate. Curious to see how it would work for scripting type applications in Windows. Quick and dirty little programs to manipulate text files and do other little tasks. Haven't gotten around to looking at Python yet though.

Brian O.
2007-07-23, 10:19 PM
Curious to see how it would work for scripting type applications in Windows. Quick and dirty little programs to manipulate text files and do other little tasks. Haven't gotten around to looking at Python yet though.
Python is excellent for that, you can do all sorts of actions like that with very little code.

uni57
2007-07-24, 07:30 AM
I've decided I wanted to try my hand at programmingThat is a Most Excellent Thing To Do! I'm even tempted to use the "A" word, but harper might be listening.

I don't know anything about Python. Why don't you post your questions and experiences here regarding Python and programming in general? I would be interested in "listening in" and helping out if I could.

john_childs
2007-07-24, 08:17 AM
Python is excellent for that, you can do all sorts of actions like that with very little code.
I took a quick look at the Python documentation and some of the tutorials. The file handling and string handling looks good and not too verbose. Regular expression support makes that all handy too. Even has support for operating on the Windows Registry. Looks good for quick and dirty little tools.

I've used Perl for text processing on files but never liked it. It got the job done but never felt good and the code looked ugly.

I've been using small C# programs for some tools. But C# (and .NET) doesn't have an interpretive or interactive mode so is not so handy for quick little things.

Python looks to have the good stuff and code that is mostly clear.

It will be worth a deeper look once I get time.

Bennedetto
2007-07-25, 06:59 PM
I wish that I could use something good like python at my work... stupid VB6.

Euch.

Brian O.
2007-07-25, 07:21 PM
I wish that I could use something good like python at my work... stupid VB6.

Euch.
Ouch, what are they having you still work on with VB6?

Bennedetto
2007-07-25, 07:24 PM
Well I mostly do work with SQL. One part of that is doing DTS packages (Data Transformation Services). Unfortunately, if I have to do any coding in that... its in VB6.

More and more of our clients are starting to use SQL 2005, so I get to work with SSIS then (the new version of DTS). Thankfully, it uses .NET, so I can go back into my lovely C#.

j-n
2007-07-25, 07:54 PM
I've decided I wanted to try my hand at programming a little bit, and I've chosen to learn the Python language, mainly because Blender3D utilizes it for the game

I'm no expert in python, but I know this and that about different programming languages and I was quite interested in ehrm.. let's call it computer linguistics :)

Nevertheless I wanted to encourage you a bit: you've made quite a good
choice (another good one could be ruby) mostly because python is easy to
learn and it's quite modern language with nice features.
Go for it, dude!

evil-nick
2007-07-26, 03:30 PM
What OS are you learning in? And are you running your program from the interpreter, or from the command line (if you're using a *nix like OSX/Linux/BSD)? Python is a good choice for learning, not only because it's powerful, but also because it forces you to indent your code which really helps readability. Besides, once you learn the basics of coding (loops, conditions, etc) switching to another language is just learning grammar. :D

dudewithasock
2007-07-26, 03:45 PM
I'm on Vista right now, and I'm using this interpreter called IDLE that came with the install, though it's sometimes a bit flaky.

uni57
2007-07-27, 03:07 AM
Hi, Nick. (we met at Joe Merrill's MUni weekend)

I never indent. In fact, it takes out my indentation if I try to put it in. What should I do? Here is a code sample of what I'm talking about...

10 PRINT "NAME? ";
20 INPUT N$
30 PRINT N$; " IS AWESOME!"
40 GOTO 30

I mostly agree with your comment that learning a new language is largely learning the new grammar and syntax. But some languages (FORTH, object-oriented languages, and non-procedural languages) require you to think differently. Python is probably a great language to start with. It will allow Matt to get a lot done without a lot of headache. And leave the door wide open for learning a whole host of languages.

dudewithasock
2007-07-27, 03:19 AM
Dave, is that python? I haven't learned those shortcuts...the tutorial I was doing would have me type:

print "Name?"
n = raw_input(" ")
print n, "is awesome!"

uni57
2007-07-27, 03:50 AM
Sorry, it was a joke (that Nick would get). The language is ancient BASIC. You can tell it's an old dialect of the language because of the line numbers. My example code is something you would write as a first program on your home computer 25 years ago (like on a VIC 20 or an Apple II or a Texas Instruments TI-99/4A or a TRS-80). I should have labeled it as a joke for all the people who wouldn't recognize the language. Oops. :)

Anyway, my program prints the same line forever. Can you add an infinite loop around the print line? Also, you need a space before the word "is" in the string, otherwise it gets mashed against the name (like: Alexis awesome). Nice job reading a language that (I assume) you never saw before and writing (almost) the equivalent in Python.

dudewithasock
2007-07-27, 03:56 AM
Oh, heh. See, that's how much of a noob I am. I kind of figured it would make an infinite loop though, makes sense. I think to do that in python (more to test myself)...

print "Name?"
n = raw_input(" ")
while 1 == 1:
print n, " is awesome!"

Bennedetto
2007-07-27, 04:03 AM
Sorry, it was a joke (that Nick would get). The language is ancient BASIC. You can tell it's an old dialect of the language because of the line numbers. My example code is something you would write as a first program on your home computer 25 years ago (like on a VIC 20 or an Apple II or a Texas Instruments TI-99/4A or a TRS-80). I should have labeled it as a joke for all the people who wouldn't recognize the language. Oops. :)

Anyway, my program prints the same line forever. Can you add an infinite loop around the print line? Also, you need a space before the word "is" in the string, otherwise it gets mashed against the name (like: Alexis awesome). Nice job reading a language that (I assume) you never saw before and writing (almost) the equivalent in Python.


What do you mean as a first program! Any real coder knows the first thing you ALWAYS write when learning a language is Hello World!

uni57
2007-07-27, 04:05 AM
Nice, but the 1 == 1 looks a little funny. In some languages an integer can be used as a boolean value (a conditional value, that is, the thing that an "if" or "while" statement is testing). In C, zero means false and any other value means true. So, in C, while (1) would be a common (idiomatic) way to write an infinite loop.

So, knowing nothing about Python other than the code you have just posted, how about...

n = raw_input("Name? ")
while 1:
print n, " is awesome!"I'm guessing about what raw_input does, but since you put the space there, I'm assuming it prints out whatever you pass it. So I simplified it a bit, but it might not be right.

Do any of my changes work?

dudewithasock
2007-07-27, 04:08 AM
Yeah raw_input() is just asking the user for some input text to name a variable. Also can do just input() for numbers.

And yeah, I just tested out 'while 1:', and it works too. I just figured 1 == 1 would work cause it seems like the most obvious way to make a constantly true statement.

evil-nick
2007-07-27, 04:46 PM
True, OOP languages take a bit of mind-reworking, but once you understand the idea behind an object, the loops are the same (Ignoring the fact that I've written one C++ program in the last year, without using objects :P)

Now, who wants to write "Hello World" in Brain F*ck? ;)

dudewithasock
2007-07-27, 04:50 PM
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.

Yeah, I wiki'd. :p

uni57
2007-07-28, 03:24 AM
What do you mean as a first program! Any real coder knows the first thing you ALWAYS write when learning a language is Hello World!Bennedetto -- I said "a first program" not "THE first program", (sloppily) meaning ONE OF the first programs you write. (and yes, I know you cannot have more than one "first program".) Also, I was programming seven years before you were born. In those days, we didn't have the instant communication that we have today. I didn't know anyone else who had a home computer. I was learning to program on my own. It was years before I saw my first official "Hello, World!" program. And in 1979, I don't really remember the bookstores having much of a computer section. However, home computers exploded onto the scene around that time, plus the IBM Personal Computer came out in 1981 -- the bookstores were quickly filled with computer books and magazines. It was a revolution. And the birth of an industry. Imagine having a computer of your very own! It was a magical time.


Matt -- I don't know if you remember I had "20 GOTO 10" in my sig for a while. A super-easy, beginner program to write in the home computer days (late 70s, early 80s) was...

10 PRINT "some message"
20 GOTO 10

... so it filled up the TV screen with the message (many early home computers were hooked up to TVs). That's what my sig referred to (similar to the BASIC program I posted earlier in this thread). You have to understand the times: Computers often had cassette players to load and save programs. No disk drives, no mouse. If someone came over who had never seen a computer before (pause to think about that for a moment), you could quickly type in that two line program and run it -- just to demonstrate the computer doing something (something other than turning it on and seeing the READY prompt). You could even put their name in the message to get some extra ooooh's and aaaaah's from your audience (they were easy to please back then).

My first computer had no sound, no bitmapped graphics, and no color (that was okay, because we didn't have a color TV to hook it up to anyway). It could use a portable cassette player for loading and saving programs (and data, if you were really sophisticated). I would always store programs at the beginning of the tape, just to make it easy to find (to load a program, you had to position the tape and press PLAY on the cassette player and then issue a LOAD command on the computer). Stuff was written to the tape as sound, I think the same way a modem transmits binary data over the telephone as sound. (edit: by the way, a modem is a modulator / demodulator, whatever that means.)

So, unless you had a cassette ready to pop in, the easiest way to show the computer doing something was to type something in. That two liner is a classic. Quick to type. And the people you are showing it to could understand the program.

Computers were about programming and learning all about how they worked. Today, they are about games and Internet and entertainment. They are an entertainment and communication appliance. Most people don't care about how they work any more than they care about how their toaster works. I miss the good old days. And I'm glad you are interested in learning to program. I hope you experience the magic that I did when I first learned to program.

Anyway, sorry for the distraction, the reminiscing, and the BASIC code. I now return this thread back to the topic of Python (and learning to program in general)...

dudewithasock
2007-07-28, 03:56 AM
Heh, very nice reminiscing, Dave. :D

Ok well I have a lot of the basic syntax/lingo down for Python now, but I'm a huge noob at the actual uses of programming...could someone give me any advice concerning something simple I could try and code and then actually use?

uni57
2007-07-28, 05:28 AM
How useful do you want it to be? You could write a utility to look at all the files on your hard drive and list the largest files (useful if you are running out of space).

You could use the "dir" command to do all the heavy lifting. The program could parse the output of the dir command, store the info for each file in an array, sort the array by file size, then list out the largest files.

It's a bit advanced, but we could take it one step at a time and work our way up to the final version.

You would have to learn how to --

- read the lines of text in a file
- parse a line of text (see the fine print below for what that means)
- store things in an array
- sort the array
- write text to a file

You could focus on accomplishing one reasonably simple thing at a time. By the time you put it all together, you would have something useful. And even after that, there would be several modifications you could do to make it more sophisticated (like traverse the directories right in Python without using the dir command).

I don't know how interactive you want this to be -- I would have to keep giving you little pieces to work on as you build your way up to the end result. Maybe you prefer something more self-contained that you can just go off and totally do on your own. It might be good for you, however, to get inside the mind of a veteran programmer, going through the design process together (with you doing all the actual programming). I would rather enjoy doing this with you.

This is just a thought. There are a bunch of people here who are just as qualified to help you (and maybe have better ideas for what to write, too).

My idea would have you write simple things that by themselves would not be very useful or interesting. But put all together, they would create a useful utility. Each step along the way would indirectly focus on fundamental programming concepts, too (sometimes unbeknownst to you). Plus you would have the benefit of the experience of creating something that is too complicated for you to think about all at once in the beginning, but by breaking it down into manageable pieces, it becomes possible.

For example, to read lines from a text file and put them in an array then sort the array would be too much all at once. So...

- learn how to add entries to an array the simplest way possible
- then figure out how to print the array elements out (so you can see what you put in)
- now write a loop to add elements to the array
- now that you have stuff in an array, learn to sort the array
- learn to read lines of text from a text file (just read a line and print it out)
- since now you know how to add stuff to an array -- and you know how to read lines of text from a text file -- as you read each line of text from the text file, add it to the array

This is one-third of the utility I propose that you write. We could go over each step one-by-one, similar to the above, but in more detail.

Again, just a thought. Feel free to say no!

By the way, the dir command spits out something like this, which your program would have to pick apart to get the file sizes and file names (which is what I mean by "parsing" above) --

01/28/2007 09:51p 2457504 DSCF4966.JPG
01/28/2007 09:51p 2512206 DSCF4967.JPG
01/28/2007 09:57p 2467541 DSCF4968.JPG

The file size comes right before the file name. Everything lines up in neat columns. I'm sure there's some sort of substring thing in Python that lets you grab pieces out of the middle of a string. Once you can read a text file, you can read the output of the dir command. You can then use substring to pick out the pieces of each line to get the sizes and file names.

gabetheunicycleman
2007-07-28, 10:57 AM
forget blender... pm me and ill send ya maya unlimited.

dudewithasock
2007-07-28, 03:44 PM
gabe: Ummm, no. Sorry. Blender for life. Can't beat a free, open-source game engine/animator/modeler/texturer/physics engine/renderer with dozens of powerful plugins and customizable python scripting to enhance it. Thanks for the offer though.

dave: Alright, I'll give it a try. I need to read up on arrays, they're really new to me, but I'll probably start working on this some time today.

dudewithasock
2007-07-28, 05:59 PM
Ok I have a question/slight problem...

IDLE isn't working for me, so I'm trying to run a little 2-line program called abc.py in the command prompt. I already changed my environment variables to easily use Python in the prompt, and I've tried using "import abc.py", and it let me run the program the first time...with an error at the end. I tried again and it didn't run it this time. I'm not really sure what the error means. Can anyone help me out?

*Edit: If it matters, I typed the program in a text editor and saved it as .py in the home python directory.

21365

uni57
2007-07-28, 06:43 PM
I'm learning Python. I just spent an hour reading the tutorial and some reference material.

What I'm doing is using a text editor to create a source file and then using the python command to execute it. No fancy tools. So, it looks like we are doing the same thing. I think that's a good way to start (simple).

I don't understand the nature of the error message, but I read somewhere that the statements in a module are only executed the first time a module is imported ("import" is for use with modules). I don't think you want to be using modules right now anyway. They are just introducing needless complexity and there are other ways to get your program into the command-line Python thing.

I would create your source file (abc.py) in C:\Users\Matt and run it with

python abc.py

If you want to stay in Python after the program ends (so you can look at variables and stuff), you can do

python -i abc.py

Edit: and to run it again, you would have to get out via quit() and then run the python command again.

dudewithasock
2007-07-28, 08:54 PM
Actually Dave, I didn't have to quit(). Worked fine for me like this:

21366

I guess it keeps working cause the environment vars were changed.

**Edit: Nvm, you must've meant when I use the -i thing I'd have to quit(). Which I do have to do.

Also, i found a couple good tutorials both on creating/working with arrays in python and reading lines from .txt files and storing/printing them, so I'll have a go at that and see if I can get it down.

uni57
2007-07-28, 09:05 PM
Don't bother with arrays. Lists will do the trick (now that I'm learning a bit of Python, I can use the correct terminology).

Try reading a file and just printing out each line that you read.

Then instead of printing the line, try writing the line to a file.

Then change it to accumulate the lines in a list (after you've read the file into a list, loop through the list and write it to a file -- this gives the same result as the previous version, but you are now learning about lists).

This is how I'm learning the language. I'm trying one very small thing at a time. I don't move on until I get it working.

dudewithasock
2007-07-28, 09:15 PM
I'm learning all the nice fileHandle() commands right now.

One thing that's kind of confusing me is the syntax this tutorial is using that it doesn't explain well for printing a line:

fileHandle = open ( 'test.txt' )

print fileHandle.readline() # "This is a test."

fileHandle.close()

Why is he using the pound sign and typing out the first line of the .txt file? It doesn't really explain how I could read, say, the 5th line.

I tried putting an integer argument for readline() but that reads a certain number of characters, not just a line of my choosing.

uni57
2007-07-28, 09:25 PM
The # sign indicates a comment (comments are notes for humans and are ignored by Python). I don't know why he put that comment there.

Also, you generally read the entire file from start to finish, one line at a time. There's no way to position to the fifth line without reading all the lines before it.

infile = open( "myfile.txt", "r" )
while True:
line = infile.readline()
print line


I didn't read my file this way because I couldn't figure out how to end the loop. Here's what I did (I found this in the tutorial).

infile = open( "myfile.txt", "r" )
for line in infile:
print line

dudewithasock
2007-07-28, 09:30 PM
This is a bit offtopic from what we're working on, but it's slowly starting to dawn on me all the customization the user has when working with any programming language...I kept thinking fileHandle was just the right term one needed to handle files, but apparently my (aptly?) named 'blargle' variable does the trick too.

I'm such a noob. :D

Also I tried what you did, the for line in var, and it worked fine. Does the "r" mean "read-only"? Cause I've learned the "w" is rewriting the file and "a" is appending it.

uni57
2007-07-28, 09:37 PM
Have you looked at the tutorial that comes with Python?

You can get to it from the Start menu.

Start / Program Files / Python 2.5 / Python Manuals

When it opens, find the tutorial. Section 7 in the tutorial (Input and Output), if you scroll down a bit, talks about readline. It also gives an example of using the "for" statement to read an entire file one line at a time.

From the tutorial --
for line in f:
print line,


Ah, I previewed my post and saw your new post. Yes, "r" is to read an existing file. Use "w" to write to a file, which creates a new file (if the file already exists, it is blown away first, so be careful). I don't know where I read about the open modes ("r", "w", etc), but they are fairly common among other programming languages (so I kind of cheated).

Be happy with your noob status. Everything is new and fresh and wonderful. Don't rush the learning process. Marvel at everything and have fun. The magic is just beginning.

dudewithasock
2007-07-28, 09:40 PM
Alright I'm currently working with piece of code I wrote from a tutorial:

filehandle = open('scripts/readlinetest.txt')

print filehandle.readline()

print filehandle.tell()

print filehandle.readline()

filehandle.close()

Which is supposed to read the first line, tell me how many bytes python's read, and read the second line. In the text doc, line 1 is 6 characters long, and filehandle.tell() prints '8'. Is this accounting for the '\n' that's needed for a line break?

uni57
2007-07-28, 09:54 PM
This is a bit offtopic from what we're working on, but it's slowly starting to dawn on me all the customization the user has when working with any programming language...I kept thinking fileHandle was just the right term one needed to handle files, but apparently my (aptly?) named 'blargle' variable does the trick too.This is exactly on-topic! You are not just learning Python. You are learning to program. That's why I thought doing it together would be better for you. You need to get started on the right foot. With someone helping you, you will gain insights like that one, possibly easier than you could from a book or online tutorial. There are fundamental programming concepts that you need to learn (that transcend any particular language). Stuff beyond the language mechanics (beyond how do I loop, etc). Certain programming practices will allow you to better manage complexity, to tackle the problem one step at a time, to make it easier to modify the program in the future, to make it easier to re-use parts of your program in a different program. And a whole lot of other things. How far you go depends only on your interest level and the amount of time you wish to dedicate. To me, it's a hobby and a career and a way of thinking. I am continually amazed that someone is willing to pay me so much money to have fun and to play with their "toys" (it's not always fun, but often it is, and often it comes close).

Also, this is your first "aha!" of many. Congratulations!

monkeyman
2007-07-28, 10:00 PM
Nerdiest. Thread. Ever.


:p

uni57
2007-07-28, 10:07 PM
In the text doc, line 1 is 6 characters long, and filehandle.tell() prints '8'. Is this accounting for the '\n' that's needed for a line break?Exactly. On Windows, lines in a text file end with CRLF -- with a carraige return / linefeed pair of characters (two characters). That accounts for the difference between six and eight. On Unix, they just use a linefeed, so tell() would have reported 7.

You probably don't need to worry about tell() because I rarely encounter a need to reposition a file (to start reading at a different location). By the time you need that capability, you will know what to do.

FYI, when you do something like...

MyOutputFile.write( "hello there\n" )

... the \n puts the line terminator character (or characters) -- as appropriate for the operating system. On Windows \n would put the CR/LF characters but on Unix it would just put the LF character.

Also, I was just thinking about when you read the file. They just give you the linefeed character in the string. They strip out the carraige return. That way, when you READ a file, it works the same on any operating system.

Anyway, the bottom line is that Python is insulating you from operating system differences. It tries to hide the fact that Windows uses a carraige return. However, tell() cannot lie to you -- the carraige return is really in the file and it takes up space -- so tell() MUST report the accurate file position of 8.

You can really ignore all this until much later in your learning process.

uni57
2007-07-28, 10:08 PM
Nerdiest. Thread. Ever.Then I must be the nerdiest person ever. Because this is my life.

You should learn Python with us.

dudewithasock
2007-07-28, 10:19 PM
Ok, the next part of this tutorial is importing some basic modules (os, time, and stat) and introducing dictionaries in order to give me info about a file. But the command line doesn't like the tutorial's code:

import os
import stat
import time

fstats = os.stat ("scripts/readlinetest.txt")

fileInfo = {
"Size" : fstats[stat.ST_SIZE],
"LastModified" : time.ctime ( fstats[stat.ST_MTIME] ),
"CreationTime" : time.ctime ( fstats[stat.ST_CTIME] ),
"Mode" : fstats[stat.ST_MODE]
}

for infoField, infoValue in fileInfo:
print infoField, ":" + infoValue

if stat.S_ISDIR ( fstats[stat.ST_MODE] ):
print "This is a directory."
else:
print "Non-directory."

It's coming up with an error at "for infoField, infoValue in fileInvo" that says:

too many values to unpack

Any idea what should be done?

dudewithasock
2007-07-28, 10:20 PM
Nerdiest. Thread. Ever.


:p

While I agree with you, I don't agree with Dave...you'd end up outlearning me too quickly :p

uni57
2007-07-28, 11:56 PM
too many values to unpackAny idea what should be done?It gave me the same error. I rewrote the code to make it simpler, which also avoids the problem of unpacking the tuple. I also added some print statements at the end to show what's really going on.

import os
import stat
import time

filename = "scripts/readlinetest.txt"

fstats = os.stat( filename )

print "Filename: " + filename
print "Size: " + str(fstats[stat.ST_SIZE])
print "LastModified: " + time.ctime ( fstats[stat.ST_MTIME] )
print "CreationTime: " + time.ctime ( fstats[stat.ST_CTIME] )
print "Mode: " + str(fstats[stat.ST_MODE])

if stat.S_ISDIR ( fstats[stat.ST_MODE] ):
print "This is a directory."
else:
print "Non-directory."

print "\n---------------------------------------\n"

print "This is the list that os.stat() returned:"
print fstats

print
print "Here are the subscripts into that list:"
print "List element " + str(stat.ST_SIZE) + " is the size"
print "List element " + str(stat.ST_MTIME) + " is the modification date"
print "List element " + str(stat.ST_CTIME) + " is the creation date"
print "List element " + str(stat.ST_MODE) + " is the mode"



I'm getting the file stats for a different file, but here's what it says when I run my version...

Filename: scripts/readlinetest.txt
Size: 115464
LastModified: Sat Jul 28 16:14:52 2007
CreationTime: Sat Jul 28 13:54:41 2007
Mode: 33206
Non-directory.

---------------------------------------

This is the list that os.stat() returned:
(33206, 0L, 0, 0, 0, 0, 115464L, 1185657640, 1185653692, 1185645281)

Here are the subscripts into that list:
List element 6 is the size
List element 8 is the modification date
List element 9 is the creation date
List element 0 is the mode

Also notice how, in my version, I put the filename in a variable? This lets me use that value in more than one place without duplicating the value. If I want to show info for a different file, I can just change the one line of code. And later, I can pass the name as a parameter to the program. I would only have to change the beginning of the program (to take the parameter and put it into my variable).

I'm still trying to figure out what the original problem was. Did you read anything about tuples? They are sort of multiple values that can go where normally a single value is stored. For example

# store a three-value tuple in one variable called t
t = ( 1, 2, 3 )

# now unpack it into three separate variables
x, y, z = t

# at this point, x = 1, y = 2, and z = 3

# and this gives a run-time error because
# there are not enough values
# (four variables but only three values in the tuple)
a, b, c, d = t


I understand what they are trying to do in the example, but I don't see what is wrong with it yet. Try running the original example with -i so you stay at the Python command line after you get the error.

Such as

python -i example.py

After it stops, take a look around at everything. Print fileInfo. It seems to be evenly paired. My version of the example prints a bunch of things. You can do similar things to debug the program -- by either typing print statements at the command line or by adding print statements throughout the program, so you can see values as it is running.

I'm going to resume watching "The Edge" now to see if Anthony Hopkins gets eaten by the bear, but I'll be around tonight (but probably not tomorrow).

gabetheunicycleman
2007-07-29, 02:10 AM
maya is a $7000 modeling, rendering, dynamics, animating etc suite! its used in movies.!

dudewithasock
2007-07-29, 02:34 AM
So?

Blender has a GE and is open-source, meaning free, legal, community-built, and heavily documented. I'll trust that over an over-priced industry whore.

evil-nick
2007-07-29, 04:09 AM
Open Source is Awesome :D

monkeyman
2007-07-29, 04:25 AM
Then I must be the nerdiest person ever. Because this is my life.
No, nerds are supposed to be in poor health. From your rants about processed anything, I doubt you're in bad shape.

You should learn Python with us.
Nah, to be honest, computer programming has never been of that much interest to me.

dudewithasock
2007-07-29, 03:42 PM
No, nerds are supposed to be in poor health. From your rants about processed anything, I doubt you're in bad shape.

I'm not in poor health...I think...

Dave: I didn't get a chance to work on any more coding last night, but later today I'm gonna try and get the code working for displaying info about a file. Once I can write that from scratch without looking, I'll move on to the next step.

uni57
2007-07-29, 06:37 PM
Dave: I didn't get a chance to work on any more coding last night, but later today I'm gonna try and get the code working for displaying info about a file. Once I can write that from scratch without looking, I'll move on to the next step.Cool. I'll probably be around. It's not a job. Take it at your own pace.

You are taking a different approach than I did (I wrote the same program yesterday). My approach used the dir command to get all the file info. A batch file will direct the output of dir to a file. So, I only had to figure out how to read a file, manipulate some strings, store things in a list, and write the output to a file.

Your design (which is much more sophisticated), will require you to recursively traverse the directory structure. You will have to learn recursive programming, which is a little bit advanced (and fun). I had let dir do that part for me. And I was trying to avoid you learning recursive programming too soon.

I don't actively try to remember everything. You will always have the documentation in front of you when programming Python. Re-coding it from scratch without looking is an interesting idea. Let me know how that works out. Personally, I would rather know how to look up something fast (like stat.ST_SIZE), rather than memorize it. Eventually, you will memorize the important stuff and have a feeling for the rest (and know where to look it up). That's just the way I work. YMMV.

dudewithasock
2007-07-29, 09:51 PM
Ok well I slightly modified the code you had to make it look how I wanted, plus put in a user-input variable so you can choose whatever file/directory you want information on without changing the script. But I understand all of it.

uni57
2007-07-29, 11:36 PM
Did you define any functions in your program? You need to start organizing your programs that way. It makes everything modular. Plus, when writing the program, you only have to focus on one small part at a time (i.e. - get this function to return the correct results). Soon you will have many functions which are the building blocks of your program (and future programs). You know how to use raw_input(), for example. You don't need to know how it works -- you just need to know what it does. Functions that you write are like that. Once you write them, you can use them everywhere without thinking about the details of how they work. They become part of your toolkit, so to speak. They are an abstraction. To get file info, you have to think about os.stat() and getting things out of the tuple that it returns. A nice function to write would be one that returned file info for any filename passed to it. Once you write that function and get it working, you never have to think about all those details again. You just think "I need to call my function." And while you are writing that function, you don't have to think about OTHER details, like "Where is the filename coming from? I could prompt the user or I can have them pass it as a parameter to the program." As you write the function, put those details out of your mind. The filename is passed to the function. Simple. Given a filename, how do I get info about it? That's all you have to think about. And once the function is working, you just have to remember how to call it.

I took the example program and organized it to include a function...

The problem is that the program fails if the file does not exist. We have to figure out how to catch the exception and return to the caller something sensible (so that the caller of the function can easily determine whether the file exists).
import os
import stat
import time


# ----------------------------
# functions...
# ----------------------------

# function to return file info
# this will return a tuple that looks like this:
# ( filename, isdirectory, size, creationtime, modtime )
# example:
# ( "myfile.txt", False, 1024, 1185657640, 1185653692 )
#
def get_file_info( filename ):
# stat the file...
fstats = os.stat( filename )

# gather some info...
size = fstats[ stat.ST_SIZE ]
isdir = stat.S_ISDIR( fstats[stat.ST_MODE] )
ctime = fstats[ stat.ST_CTIME ]
mtime = fstats[ stat.ST_MTIME ]

# build the return value (a tuple)...
retval = ( filename, isdir, size, ctime, mtime )

# and return it to the caller...
return retval

# ----------------------------
# beginning of main program...
# ----------------------------

# notice that the variables you used in the function
# are LOCAL to that function. They do not exist out here.
# (try accessing fstats or retval -- they only exist when
# you are inside the function)

name = raw_input( "Filename? " )

info = get_file_info( name )

print "Filename: " + info[0]
print "Size: " + str( info[2] )
print "CreationTime: " + time.ctime ( info[3] )
print "LastModified: " + time.ctime ( info[4] )
print "Directory: ",
if info[1]:
print "Yes"
else:
print "No"

uni57
2007-07-29, 11:49 PM
Also, notice how I could have printed the file info from within the function. I could have called it print_file_info().

But... this would not be a very useful function. Usually, I don't want to PRINT the info about a file, I want to examine it and do something else with it.

So, a much more useful function is one that returns file info. After you call the function, you have the file info to do with as you wish. Print it. Look at it. Put it in a list. If we combined too much into the function, it loses its general usefulness. Here's something to think about: If I really did want a function to print file info, I would write TWO functions. One to get the file info, the other to print it. The print function can call the get function, and the get function is a very handy function to have in the future (maybe in a different program). Getting file info and printing file info are completely different tasks. Why would I want to think about both at the same time? By writing two functions, you limit how much you have to think about all at once. And you end up with more useful building blocks.

You have to think about the usefulness of a function when you decide what to put in it. If you make it too specific to the task at hand (print the file info), it does not fit into other parts of your program (or future programs). If you make it too general, you end up coding too much stuff that you will possibly never use. Anyway, knowing the difference comes with practice.

dudewithasock
2007-07-30, 12:24 AM
Very nice lesson about functions. I already knew how to define/call functions as well as how to pass arguments to them, but I never really know when to use them and how big to make them. What you wrote helped a lot.

Also, I went on to the next lesson in this tutorial, which is just handling directories, which was fairly simple.

leo
2007-09-30, 08:26 PM
Today I wrote a whois server in python, it queries a MySQL db.
Just for fun, but I think in the end I'll offer it to a ccTLD NIC that has no yet.
It's the 1st big thing I did in python. I like the error messages, very friendly.

GILD
2007-10-01, 12:29 PM
Anyone familiar/proficient with Python?
I'm not!