簡體   English   中英

Python代碼將stdin和stdout重定向到Shell腳本

[英]Python code to redirect stdin and stdout to a shell script

我正在嘗試編寫一個程序,該程序從文件讀取並使用命令行將其寫入新文件。 我正在使用CommandLine類,並使用ArgParse接受不同的args以及用於輸入和輸出的文件名。 我正在嘗試將stdin和stdout重定向到這些文件。 但是,我不斷收到一個錯誤,該錯誤出現在下面的代碼底部。 我是否在命令行中輸入了錯誤的參數,還是發生了其他情況? 我所有的文件都在同一個文件夾中。

class CommandLine() :
'''
Handle the command line, usage and help requests.

CommandLine uses argparse, now standard in 2.7 and beyond. 
it implements a standard command line argument parser with various argument options,
a standard usage and help, and an error termination mechanism do-usage_and_die.

attributes:
all arguments received from the commandline using .add_argument will be
avalable within the .args attribute of object instantiated from CommandLine.
For example, if myCommandLine is an object of the class, and requiredbool was
set as an option using add_argument, then myCommandLine.args.requiredbool will
name that option.

'''

def __init__(self, inOpts=None):
    '''
    CommandLine constructor.
    Implements a parser to interpret the command line argv string using argparse.
    '''

    import argparse
    self.parser = argparse.ArgumentParser(description = 'Program prolog - a brief description of what this thing does', 
                                         epilog = 'Program epilog - some other stuff you feel compelled to say', 
                                         add_help = True, #default is True 
                                         prefix_chars = '-', 
                                         usage = '%(prog)s [options] -option1[default] <input >output'
                                         )
    self.parser.add_argument('inFile', action = 'store', help='input file name')
    self.parser.add_argument('outFile', action = 'store', help='output file name')
    self.parser.add_argument('-lG', '--longestGene', action = 'store', nargs='?', const=True, default=False, help='longest Gene in an ORF')
    self.parser.add_argument('-mG', '--minGene', type=int, choices= (0, 100, 200, 300, 500, 1000), action = 'store', help='minimum Gene length')
    self.parser.add_argument('-s', '--start', action = 'append', nargs='?', help='start Codons') #allows multiple list options
    self.parser.add_argument('-st', '--stop', action = 'append', nargs='?', help='stop Codons') #allows multiple list options
    self.parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1')  
    if inOpts is None :
        self.args = self.parser.parse_args()
    else :
        self.args = self.parser.parse_args(inOpts)

C:\Users\Zach\Documents\UCSC\BME 160\Lab 5>python findORFsCmdLine.py --    minGene=3
00 --longestGene --start=ATG --stop=TAG --stop=TGA --stop=TAA <tass2.fa     >result.
txt
usage: findORFsCmdLine.py [options] -option1[default] <input >output
findORFsCmdLine.py: error: the following arguments are required: inFile,     outFile

該錯誤告訴您您未提供inFileoutFile 這似乎令人困惑,因為您確實在命令行上提供了<tass2.fa>result.txt

在命令行<>具有特殊含義。 <tass2.fabash (或您使用的任何shell)處理,並打開文件tass2.fa並將內容通過stdin發送到您的程序。 然后,它將它從命令行參數列表中刪除,因為bash已經處理了它。

>result.txt也會發生類似的情況,文件中的任何正常輸出到stdout例如打印調用)都將寫入該文件。 bash再次處理此問題,因此您的程序永遠不會從命令行獲取參數。

為確保文件名進入程序,您需要刪除<>符號。


除此之外,你現在的樣子通話add_argumentinFileoutFile是不正確的。 使用action='store'只是將參數的值存儲在給定名稱下。 這是默認操作,因此這樣做是多余的。

您需要告訴add_argument這些是文件類型。 然后,您可以將它們用作文件,並根據需要進行讀寫。

parser.add_argument('inFile', type=argparse.FileType('r'))
parser.add_argument('outFile', type=argparse.FileType('w'))

如果您希望允許這些參數是可選的,並且在不提供文件名的情況下自動使用stdinstdout則可以執行以下操作:

parser.add_argument('inFile', type=argparse.FileType('r'),
    nargs='?', default=sys.stdin)
parser.add_argument('outFile', type=argparse.FileType('w'),
    nargs='?', default=sys.stdout)

您說您正在編寫一個程序,該程序可以從文件讀取並使用命令行將其寫入新文件,然后繼續說您正在嘗試將這些文件重定向到stdin和stdout。

如果確實打算使用帶有><運算符的shell重定向輸入和輸出文件,則根本不需要使用outFile調用add_argument 只需讓外殼處理它即可。 從程序中刪除該行,並使用print或類似方法將您的內容發送到stdout ,然后將創建該文件。 您仍然需要調用add_argument('inFile', ...

暫無
暫無

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

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