簡體   English   中英

如何運行將文本文件作為輸入的python文件?

[英]How do I run a python file that takes a text file as input?

所以基本上我想在命令行中運行一個python文件,該文件讀取文本文件並顯示信息。

我想這個問題的一部分還在於文本文件是否應該與python文件位於同一目錄中?

這就是我所擁有的,我認為就代碼方面而言,這是正確的。

  def print_words(filename):
        input_file = open(filename, 'r')
        print (input_file)

   print_words(filename)
import sys

def print_words(file_name):
    input_file = open(file_name, 'r')
    lines = input_file.readlines()
    lines = ' '.join(x for x in lines)
    print(lines)

if __name__ == '__main__':
    print_words(sys.argv[1])

filename可以是文件名的時候它是在同一文件夾中.py文件。 否則,完整路徑作為filename也將起作用。

編輯:sys.argv [1]將第二個命令行參數作為filename 這可以是絕對或相對filename

例如:在Windows中,當文件位於Python文件夾中時,可以在命令行中調用:c:\\ Python32> python print_words.py“ example.txt”

如果文件位於其他位置,則可以使用該文件:c:\\ Python32> python print_words.py“ C:\\ FOLDER \\ SUBFOLDER \\ example.txt”

編寫命令行腳本始於像您這樣的簡單要求(讓我僅輸入文件名),並很快導致更復雜的情況。

那時,某些命令行參數解析器很方便。

有很多選擇,其中一些是:

  • sys.argv :不是命令行解析器,在更復雜的情況下會不足
  • argparse :自Python 2.7起stdlib的一部分,但將需要多行額外代碼
  • plac :非常有用的實用程序腳本,除非您遇到更復雜的情況
  • docopt :到目前為止,我發現處理命令行解析的最好,最干凈的方法

使用docopt命令行解析

首先安裝docopt:

$ pip install docopt

然后編寫腳本readfile.py

"""Read file (and possibly convert lines)
Usage:
    readfile.py [(--uppercase|--lowercase|--swapcase)] [--reverse] <filename>...
    readfile.py -h

Options:
    -U --uppercase  Convert text to uppercase
    -L --lowercase  Convert text to lowercase
    -S --swapcase   Swap character cases
    -R --reverse    Reverse text on each line

Reads file(s) <filename>, optionally convert lines to uppercase or lowercase and 
possibly reverses text of each line.

Output is printed to stdout.
"""
import string

def get_convert_func(caseconvert="keep", reverse=False):
    funcs = {"upper": string.upper, "lower": string.lower, "keep": lambda x: x}
    casefunc = funcs[caseconvert]
    if reverse:
        return lambda line: "".join(list(casefunc(line))[::-1])
    else:
        return casefunc

def printfiles(filenames, convert_func):
    for filename in filenames:
        with open(filename) as f:
            for line in f:
                print convertfunc(line.strip("\n"))

到目前為止,我們為該文件和要調用的函數編寫了docstring。

readfile.py繼續

但是真正的解析將到來(它必須在同一文件中,放在最后):

if __name__ == "__main__":
    from docopt import docopt
    args = docopt(__doc__)
    print "args", args
    filenames = args["<filename>"]
    caseconvert = "keep"
    if args["--uppercase"]:
        caseconvert = "upper"
    if args["--lowercase"]:
        caseconvert = "lower"
    reverse = args["--reverse"]
    print "--------- Converted file content: ------------"
    convertfunc = get_convert_func(caseconvert, reverse)
    printfiles(filenames, convertfunc)

嘗試代碼

最后嘗試一下:

$ python readfile.py
Usage:
    readfile.py [(--uppercase|--lowercase|--swapcase)] [--reverse] <filename>...
    readfile.py -h

嘗試查看更多幫助:$ python readfile.py -h讀取文件(並可能轉換行)用法:readfile.py [(-大寫|-小寫| --swapcase)] [-反向] ... readfile .py -h

Options:
    -U --uppercase  Convert text to uppercase
    -L --lowercase  Convert text to lowercase
    -S --swapcase   Swap character cases
    -R --reverse    Reverse text on each line

Reads file(s) <filename>, optionally convert lines to uppercase or lowercase and 
possibly reverses text of each line.

Output is printed to stdout.

並采取一些實際行動:

$ python readfile.py -UR readfile.py ../th.py
args {'--lowercase': False,
 '--reverse': True,
 '--swapcase': False,
 '--uppercase': True,
 '-h': False,
 '<filename>': ['readfile.py', '../th.py']}
--------- Converted file content: ------------
)SENIL TREVNOC YLBISSOP DNA( ELIF DAER"""
:EGASU
...>EMANELIF< ]ESREVER--[ ])ESACPAWS--|ESACREWOL--|ESACREPPU--([ YP.ELIFDAER    
H- YP.ELIFDAER    

:SNOITPO
ESACREPPU OT TXET TREVNOC  ESACREPPU-- U-    
ESACREWOL OT TXET TREVNOC  ESACREWOL-- L-    
SESAC RETCARAHC PAWS   ESACPAWS-- S-    
....etc....

結束語

  • 忽略執行實際動作的代碼(這並不重要,但例如命令行解析並不重要)
  • 腳本文件應具有正確格式的docstring-這是docopt命令行解析規則的來源。 必須學習這些規則,但是它們並不是那么困難,並且它們能夠表達大量的不同組合。
  • docopt(__doc__)正在解析所謂的docstring,它是從腳本文件的初始"""(some strint..."""節中讀取的。
  • docopt解析的結果打印在輸出上,以顯示您從解析命令行獲得的字典。 在生產代碼中,將其刪除。
  • 該示例變得更加復雜以顯示靈活性(僅當我們不計算文檔字符串時,要求一個文件名將花費我們兩行代碼)。 巨大的優勢是, docopt導致具有非常易讀(且有效)的docstring作為腳本的基本組成部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM