Preparing Python program to be run in UNIX enviroment -


just starting using unix semester move programs repositories , curious how prep file run in enviroment...

heres code:

def main(file):     ctest = 0     words = 0     lines = 0     chars = 0     l in open(str(file)):         linewords = l.split()         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 functionality standpoint works fine when pointed on own system, is on unix being told run this....

python3 wc.py < file.txt 

how prepare file when executed in environment take text properly?

fortunately not platform dependent. have read here or somewhere else import sys , read stdin:

data = sys.stdin.readlines() 

but work begins:

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

and program expand s.th. this:

#!/bin/env python  import sys  def main():     data = sys.stdin.readlines()      word_count = 0     char_count = 0     line_count = len(data)     l in data:         linewords = l.split()         word_count += len(linewords)         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 said before: apart shell-magic , executable bit not unix specific python.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -