准备Python程序以在UNIX环境中运行

时间:2014-01-31 22:56:56

标签: python unix

本学期刚开始使用UNIX将程序移动到存储库,我很好奇如何准备我的文件以便在该环境中运行...

继承我的代码:

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))

就功能性而言,它在我自己的系统上正确指向时工作正常,但现在是在UNIX上我被告知要像这样运行它....

python3 wc.py < file.txt

如何准备文件,以便在此环境中执行时,文本是否正确?

3 个答案:

答案 0 :(得分:3)

啊,欢迎来到现实世界:

在Unix / Linux环境中,每个基于脚本的程序都以“sha-bang”开始。 “#!”然后是程序的完整路径。之后,程序只需要由env执行。这可以通过chmod命令完成。另一个小调整将使你的代码更加pyhonic,那就是使用它的__main__构造。

<强> 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. 在您的文件中添加sha-bang。
  2. 添加__main__ python构造和选项解析器来清理你的代码。
  3. 最后chmod 755你的文件。
  4. 通过将文件名作为参数传递来运行它。

答案 1 :(得分:2)

幸运的是,这不依赖于平台。您可以阅读here或其他地方import sys并阅读stdin

data = sys.stdin.readlines()

然后工作开始了:

  • 你应该有一个可执行的入口
  • 您应该使您的脚本可执行(chmod +x yourfile.py
  • 你应该让你的脚本以一些bash魔法开始(第一行)
  • 您不应将关键字用作变量名称(例如file

然后你的程序将扩展到s.th.像这样:

#!/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()

但如前所述:除了shell-magic和可执行位之外,由于Python,这不是unix特定的。

答案 2 :(得分:0)

在文件末尾添加以下内容。并遵循上面的模糊推荐。

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