如何将sys.argv添加到在Python中打开文本文件的函数中

时间:2016-04-06 01:56:48

标签: python file command-line

我需要使用sys.argv来检查命令行中的参数,在我的情况下这将是文件名。我的代码如下。我不允许导入argparse,只允许使用sys。我知道我在这里做错了。感谢任何帮助。

def get_inputfile_object( ):
    '''
    Check the command line for an argument.  If one was there, use it as the
    filename.  Otherwise, use DEFAULT_INPUT_FILENAME.  Open the file.

    If file is successfully opened:
        print MSG_OPENING_FILE
        Return: a file object for that file

    If the file cannot be opened:
        print MSG_ERROR_OPENNING_FILE
        Return: True
    '''
    if sys.argv > 1:
        pass
    else:
        input_filename = DEFAULT_INPUT_FILENAME

    input_filename = DEFAULT_INPUT_FILENAME
    if os.path.isfile(input_filename) and os.access(input_filename,os.R_OK):
        #Prints the opening file message, and the name of the file
        print (MSG_OPENING_FILE,input_filename)
        return open(input_filename,'r')
    else:
        print (MSG_ERROR_OPENING_FILE)
        return True

2 个答案:

答案 0 :(得分:0)

GoodProvider是一个参数列表。

您需要检查列表的长度:

sys.argv

答案 1 :(得分:0)

您应该查看argparse

  

argparse模块还会自动生成帮助和用法   用户提供程序无效时的消息和问题错误   参数。

Haven未经过测试,但你可以尝试类似的东西:

import argparse

# setup the parser
parser = argparse.ArgumentParser(description='Describe script')

# add positional argument
parser.add_argument('filename', type=str, help='filename description')

# parse the args
args = parser.parse_args()
print(args.filename)