Sys Admin struggling with Python

Status
Not open for further replies.

enygma

Ars Tribunus Militum
2,065
I'm a successful systems administrator, been doing it for about 15 years, and I have some spare time on my hands, so I thought I would try my hand at learning some Python. I've done basic scripting before with VBScript and batch files, but I haven't learned a real language. I know the basics of programming, such as if-then-else, program loops, variables, etc. I chose Python because I hear it's a good language to cut my programming teeth on and it's cross-platform, so I would be able to utilize it on some Linux boxes I admin as well as the Windows boxes.

As simple as I thought Python would be, it is kicking my butt. I can't wrap my head around various keywords/terms that are being used. I started with http://diveintopython.org and the first couple chapters were a breeze, but getting into lists is a bit confusing. I think I am getting overwhelmed with terminology and functions.

So, how did you learn, just start hacking away or reading material? I am very much a visual learning and books bore me to death. I would just start hacking on an idea I have, but, honestly, I'm not even sure how to start.
 

bk0

Ars Tribunus Militum
1,801
Come up with a real project and then implement it in Python. So if you have some set of batch files or VBA/VBScript that you use regularly for various functions, try reimplementing them in Python. Lists, iterators, generators and so on are fundamental to the language (and extremely useful) but I'm not sure you can really get it just by reading a book, you have to actually use them.

I might suggest avoiding object-oriented concepts at first (classes/methods/exceptions), just concentrate on program flow, scoping and writing small, self-contained functions.
 

enygma

Ars Tribunus Militum
2,065
bk0":r5889ljq said:
Come up with a real project and then implement it in Python. So if you have some set of batch files or VBA/VBScript that you use regularly for various functions, try reimplementing them in Python. Lists, iterators, generators and so on are fundamental to the language (and extremely useful) but I'm not sure you can really get it just by reading a book, you have to actually use them.

I do have an idea for an app that I would like to implement. It is basically a wrapper around a command-line utility. I have looked up examples, but I haven't found anything that gets me even remotely close to starting the project. I guess it is too advanced a topic for me right now. The most I could do right now is do some basic arithmetic on a couple numbers and output the result. Very very basic stuff. I know that I would need to import modules or something, but I have no idea which ones or how to use them. I also have no idea how to get the output in a usable form into Python. I might be able to persuade Python to run the command line utility, but that's it.
 

falcolas

Ars Scholae Palatinae
748
enygma":2akf0tmk said:
bk0":2akf0tmk said:
Come up with a real project and then implement it in Python. So if you have some set of batch files or VBA/VBScript that you use regularly for various functions, try reimplementing them in Python. Lists, iterators, generators and so on are fundamental to the language (and extremely useful) but I'm not sure you can really get it just by reading a book, you have to actually use them.

I do have an idea for an app that I would like to implement. It is basically a wrapper around a command-line utility. I have looked up examples, but I haven't found anything that gets me even remotely close to starting the project. I guess it is too advanced a topic for me right now. The most I could do right now is do some basic arithmetic on a couple numbers and output the result. Very very basic stuff. I know that I would need to import modules or something, but I have no idea which ones or how to use them. I also have no idea how to get the output in a usable form into Python. I might be able to persuade Python to run the command line utility, but that's it.
For simple command line utility wrappers with limited input/output, look at the subprocess module. If you're wanting to automate utilities with input/output, take a look at the 3rd party pyexpect (though dev has stopped on it, it still works well enough for most cases).
 

bk0

Ars Tribunus Militum
1,801
Code:
#!/usr/bin/env python3

#run a random command line program with some arguments depending upon arguments given

import sys
import os

my_command = "C:\scripts\my_script.bat"

my_args = "/a /b /c /d *.foo"

if sys.argv[1] == "do_it":
    os.system("{cmd} {args}".format(cmd=my_command, args=my_args))
else:
    print("Not doing it!")

A rather more sophisticated example that simply runs whatever batch file/shell script you supply as an argument:

Code:
#!/usr/bin/env python3

import sys
import os

with f as open(sys.argv[1], "r"):
    for line in f:
        os.system(line)    #not portable, on Windows it will pass to cmd.exe, on linux to /bin/(ba)sh, etc
 

lostnihilist

Ars Scholae Palatinae
1,436
To be fair, I think DiveIntoPython is more for programmers to learn python than for people learning to program and using Python as their first language. I would use more of a tutorial document. I'm a big fan of the "How to Think Like a Computer Scientist with Python" document. Unfortunately, its current state is in a bit of flux. The old document is, well, old, which is bad for computers. The new document is complete enough to learn by, but is missing some figures and such. You might be able to google the old version when you need help with clarity or something. Otherwise, I think you should start with this.

fwiw, wrapping command line utilities is often not the best way to do things, can get ugly, and is usually a last resort if there isn't a more native library to work with. Also, if you are wrapping command line utilities, unless those utilities behave exactly the same on all platforms, you lose the cross-platform advantage of Python. But yea, if you go there, subprocess is your friend.

phantom edit: oh, and then there is this version, which is kind of a fork with i think a different organizational structure.
 
I've heard good things about http://learnpythonthehardway.org/ (by Zed Shaw) as a Python book for beginners. Plus it's free!

The book is a very beginner book for people who want to learn to code. If you can already code then the book will probably drive you insane. It's intended for people who have no coding chops to build up their skills before starting a more detailed book.
 
I really enjoyed MIT's open-course-ware for intro to computer science, which is taught using Python. You can check it out here:
http://ocw.mit.edu/courses/electric...o-computer-science-and-programming-fall-2008/

The problem sets are challenging and the lectures proved valuable to me. Good luck! Python has been a simple and powerful tool that helped me solve many problems quickly.
 

MooseAreFun

Ars Legatus Legionis
10,827
Subscriptor
Come on man. In a sense I admire your perseverance, but maybe it's just not for you, and you should find something you enjoy instead?

viewtopic.php?f=20&t=122483

viewtopic.php?f=20&t=405120

viewtopic.php?f=20&t=522729

viewtopic.php?f=20&t=547082

viewtopic.php?f=20&t=562736

viewtopic.php?f=20&t=561947

viewtopic.php?f=20&t=565552

viewtopic.php?f=20&t=617101

viewtopic.php?f=20&t=640545

viewtopic.php?f=20&t=682633
 
MooseAreFun":e52zqrji said:
Come on man. In a sense I admire your perseverance, but maybe it's just not for you, and you should find something you enjoy instead?

viewtopic.php?f=20&t=122483

viewtopic.php?f=20&t=405120

viewtopic.php?f=20&t=522729

viewtopic.php?f=20&t=547082

viewtopic.php?f=20&t=562736

viewtopic.php?f=20&t=561947

viewtopic.php?f=20&t=565552

viewtopic.php?f=20&t=617101

viewtopic.php?f=20&t=640545

viewtopic.php?f=20&t=682633

Awesome. I'm glad you looked up the history.

Enygma,

You just need to program and stop whining. Of course it's hard, but you have to actually get started. There's no magical book out there that's going to be substantially different than anything you have read. Ditch the online tutorials: they rely on code examples too much and don't have enough text to explain material.
 

enygma

Ars Tribunus Militum
2,065
Yes, I do tend to whine a bit... sorry. I have tried a couple books, but I tend to get bored easy and then put the book down and forget about it. I guess I haven't found the right book, yet. Of course there is the possiblity, that I'm just not cut out to be a programmer of any kind, even with Python. I know you have to have a certain mindset, and I've tried the "How to think like a computer scientist" book, but it bored me to tears.
 

ahankinson

Wise, Aged Ars Veteran
117
As a wise man once said "Try not. Do or do not. There is no try."

At this stage in the game, you're not going to find a book, website or anything to make you magically learn programming. Perhaps what you need to do is post something you've written, and allow us to critique it. It might hurt, but you'll be better for it.

EDIT: I Just saw this after I posted. http://37signals.com/svn/posts/2538-the ... s-to-start

Some good advice there.
 

enygma

Ars Tribunus Militum
2,065
Blacken00100":1ck4z4ui said:
Do you expect programming to be instantly enthralling? Most of it is boring grind, with occasional moments of astonishment and intermittent patches of intellectual entertainment.

I don't expect it to be enthralling at all, but I do expect it to take hold of me so that I want to continue. There is something very intriguing about writing a program to solve a problem that keeps me coming back.

ahankinson":1ck4z4ui said:
Perhaps what you need to do is post something you've written, and allow us to critique it. It might hurt, but you'll be better for it.

There is nothing to post, I haven't written anything. I'm still trying to get started.
 
I don't expect it to be enthralling at all, but I do expect it to take hold of me so that I want to continue

This may be an unrealistic expectation. The best thing I can compare it to is learning guitar (or any other musical instrument). The first several months suck; your fingers hurt, you can't play any of the songs you like, and most of the sounds coming out of the instrument are annoying, embarrassing, and unmusical. Really, the only thing that motivates you to keep playing is you know that if you keep at it, you will eventually be able to play something worth listening to.

Programming is the same way. You have to stick with it until you make enough progress for it to start to be enjoyable because of a sense of accomplishment. In school, this sense of accomplishment can be your first homework assignment. Learning on your own, it will probably have to be a project you can complete. Don't shoot too high on your first projects or you will inevitably be disappointed.

You must be of the attitude that once you set out to do something, you will keep trying until you accomplish it.
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
enygma":3ptwlfrw said:
I don't expect it to be enthralling at all, but I do expect it to take hold of me so that I want to continue. There is something very intriguing about writing a program to solve a problem that keeps me coming back.
Expect nothing of the sort. Early programs are trivial and unimpressive and take way longer to do than you think they should and don't usually do everything you want them to do.

The upside? If you stick with it, it can be incredibly rewarding. But it requires a level of self-discipline and not everyone is cut out for it.
 
There is nothing to post, I haven't written anything. I'm still trying to get started.

OK, this is a big problem. To reference my learning guitar analogy above, the conversation would be like this:

You: "I'm looking to learn guitar. I've read a bunch of books and watched a bunch of videos but I just can't seem to get the hang out it"

Mentor: "So, what are you specifically having difficulty with? Can you describe the problems you are having learning guitar?"

You: "Oh, I actually haven't ever picked up a guitar and played it. I've watched videos and read books, but I still don't get it. I don't feel I get it."

</end analogy>

You need to actually write some code, even if it is a hello world. Write a simple program that does something like have boxes that turn the screen different colors, or any example project from any programming 101 book. You are going to have to get your hands dirty to get anywhere.
 

ahankinson

Wise, Aged Ars Veteran
117
There is nothing to post, I haven't written anything. I'm still trying to get started.

Then, in the most polite way possible: Put up or shut up.

Sit down tomorrow and write something. Write a "for" loop that prints out numbers. Hell, even steal code from somewhere and modify it. Steal an example from Dive Into Python - it's all annotated.

Take bk0's code and modify it to run your command-line utility. Run it from the command line. Input it line-by-line into the Python interpreter to see how things work there.

But we can't help you until you help yourself first.
 

enygma

Ars Tribunus Militum
2,065
Ok, so I decided to keep on going. I found some great videos from Google at: http://code.google.com/edu/languages/google-python-class/index.html. I've gone through the first three videos and I understand most everything, but the exercises are hard (for me). I've only been able to complete two in the first one. It's weird I understand the material, but when presented with an exercise, I completely forget everything. I looked at the solutions and I do a facepalm. It seems so simple, but I guess I'm just not connecting the dots.

BTW, I found some examples, and came up with this for my command line wrapper:
Code:
import subprocess as sub
p = sub.Popen('C:/bin/program.exe -l',stdout=sub.PIPE)
lines = p.stdout.readlines()
p.wait()
print lines

It gives me the output I am looking for, but it isn't very useful as I would like to take the data, format it, and display it in a GUI or something. That's in the future though.
 

ahankinson

Wise, Aged Ars Veteran
117
Here's a slightly longer example showing how you might use the OptionParser module to pass in flags on the command line. GUIs will come much later.

Code:
# import a single class from this module
from optparse import OptionParser

import subprocess as sub
import time

# see http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm
# for why you might want to use "if __name__".
if __name__ == "__main__":
    # create a new instance
    p = OptionParser()
    
    # add a flag that will store a variable.
    p.add_option("-f", "--flag", help="Store the value passed into a variable")
    
    # add a flag that will simply be "true" or "false"
    p.add_option("-t", "--trueflag", action="store_true", help="Store the value passed into a variable")
    
    # parse your commands
    (options, args) = p.parse_args()
    
    # subprocess takes a list [], so we can just pass them all in here
    binfile = "C:/bin/program.exe"
    
    # -l will always be passed in.
    command = [binfile, "-l"]
    
    # add in some of your optional flags. Remember that these are named after your 
    # options that you added above.
    if options.flag:
        command += ["-f", options.flag] # append your command's flag, and the value that was passed to your python script.
    if options.trueflag:
        command += ["-t"] # just append a command-line switch
    
    # run your command
    p = sub.Popen(command, stdout=sub.PIPE)
    
    # if the command is a long-running one, you can wait for it to terminate here.
    while p.returncode is None:
        p.poll() # check if it's done
        time.sleep(1)  # wait one second
    
    # print out stdout.
    print "{0}".format(p.stdout.readlines())
    
    # exit!
    print "Exiting!"
 

epimethee

Seniorius Lurkius
41
Subscriptor
enygma":1q0wok5d said:
I don't expect it to be enthralling at all, but I do expect it to take hold of me so that I want to continue. There is something very intriguing about writing a program to solve a problem that keeps me coming back.

Another option, if you're into gaming: mods. The difficulty level can be quite low (if you don't try to do too much) and the reward is quite visible and quick. Among the games supporting Python, the Freedom Force series and Civilization IV.
 

enygma

Ars Tribunus Militum
2,065
I think I have found a solution that works for me. I viewed the Google Course and now going through the MIT course. Once I finish these "Boot Camp" courses, I set myself some exercises to do and then just build upon that. In the past I have learned a lot just by being asked to figure something out, so, hopefully, this will go the same. I have already learned a lot just by doing the Google course, it was very enlightening, especially with the Regular Expressions video.
 

gloucester

Ars Scholae Palatinae
996
Making progress?

The Google stuff, like Dive Into Python, is mostly geared toward presenting Python's syntax and idioms to people who already know how to program. Because there's a lot more to programming than syntax, you should consider also looking a text that's more of an introduction to computer science. ...

lostnihilist":z36j9442 said:
I'm a big fan of the "How to Think Like a Computer Scientist with Python" document. Unfortunately, its current state is in a bit of flux. ... there is this version, which is kind of a fork with i think a different organizational structure.
I used Think Python (lostnihilist's "this version") to learn how to program a couple of years ago and thought it was very good. I still think so retrospectively. It's presentation is a pretty enlightening mishmash of fundamental computing topics, the ins and outs of Python data structures, and practical discussion.

If you read through the first eleven chapters (but I'd skip the interface stuff of Chapter 4) you'll have a solid enough basis to learn from other sources (the Python docs, particularly). That's only about 100 pages. Read one-ish chapter a day and you really can be programming real stuff in a couple of weeks. Do the exercises, of course.
 
Status
Not open for further replies.