BLU
BLU

Reputation: 121

Preparing Python program to be run in UNIX enviroment

just starting using UNIX this semester to move programs to repositories and I am curious as to how to prep my file to be run in that enviroment...

Heres my code:

def main(file):
    cTest = 0
    words = 0
    lines = 0
    chars = 0
    for l in open(str(file)):
        linewords = l.split()
        for w in l:
            chars += 1
        lines += 1
        words += len(linewords)
    print("Lines: " + str(lines))
    print("Characters: " + str(chars))
    print("Words: " + str(words))

In terms of a functionality standpoint it works fine when pointed properly on my own system, but now that is is on UNIX I am being told to run it like this....

python3 wc.py < file.txt

how do I prepare the file so that when executed in this environment it will take the text properly?

Upvotes: 1

Views: 138

Answers (3)

frans
frans

Reputation: 9758

Fortunately this is not platform dependent. As you could have read it here or somewhere else you just import sys and read from stdin:

data = sys.stdin.readlines()

But then the work begins:

  • you should have a executable entrance
  • you should make your script executable (chmod +x yourfile.py)
  • you should make your script start with some bash magic (the first line)
  • you should not use keywords as variable names (like file)

and then your program would expand to s.th. like this:

#!/bin/env python

import sys

def main():
    data = sys.stdin.readlines()

    word_count = 0
    char_count = 0
    line_count = len(data)
    for l in data:
        linewords = l.split()
        word_count += len(linewords)
        for w in l:
            char_count += len(w)

    print("Lines:      %d" % line_count)
    print("Characters: %d" % char_count)
    print("Words:      %d" % word_count)

if __name__ == '__main__':
    main()

but as said before: apart from the shell-magic and the executable bit this is not unix specific thanks to Python.

Upvotes: 2

Jeff Sheffield
Jeff Sheffield

Reputation: 6316

ahh, welcome to the real world:

In Unix/Linux env's every script based program starts off with a "sha-bang". "#!" then the full path to the program. After that the program just needs to be executable by the env. This can be accomplished by the chmod command. One other minor tweak will make your code a bit more pyhonic and that is to use its __main__ construct.

wc.py

#!/usr/bin/python
# where /usr/bin/python is the full path to your python.
# you can get determine this from doing $ which python

import optparse 

def word_count(file):
    """ A good programmer always documents there functions"""

    cTest = 0
    words = 0
    lines = 0
    chars = 0
    for l in open(str(file)):
        linewords = l.split()
        for w in l:
            chars += 1
            lines += 1
            words += len(linewords)
    print("Lines: " + str(lines))
    print("Characters: " + str(chars))
    print("Words: " + str(words))

if __name__ == '__main__':
    p = optparse.OptionParser(description="My Test Program", usage='%prog <filename>')
    ons, arguments = p.parse_args()
    if len(arguments) == 1:
        word_count(arguments[0])
    else:
        p.print_help()

chown the file:

$ chmod 755 wc.py
$ wc.py file.txt
  1. add a sha-bang to your file.
  2. add the __main__ python construct, and options parser to clean up your code a bit.
  3. finally chmod 755 your file.
  4. run it by passing a filename in as an argument.

Upvotes: 3

wolfrevo
wolfrevo

Reputation: 7303

add the following at the end of your file. And follow the recomendation of squiguy above.

import sys
main(str(sys.argv[0]))

Upvotes: 0

Related Questions