如何在此代码中添加带参数的更多功能?

时间:2016-09-28 21:25:00

标签: python

我找到了很好的小程序,可以在终端上做快速笔记。功能有点缺乏 - 我无法阅读我用它做过的笔记,也无法清除文件中存储的笔记。我想修改这个程序,所以我可以用参数运行它来阅读我在那里写的内容并清理。我有一些想法如何做到这一点,但无法在代码中找到写入位置来粘贴我的行。我想用以下参数运行它:-r -c

原始程序如下所示:

#!/usr/bin/env python3

import time
import os
import sys

# add the current local time to the entry header
lines = [ time.asctime() + '\n' + '--------------------\n' ]

if len( sys.argv ) > 1:
    lines.append( ' '.join( sys.argv[ 1: ] ) )
    lines[-1] += '\n'
else:
    while 1:
        try:
            line = input()
        except EOFError:
            break

        # get more user input until an empty line
        if len( line ) == 0:
            break
        else:
            lines.append( line + '\n' )


# only write the entry if the user entered something
if len( lines ) > 1:
    memoir_path = os.path.expanduser( '~/.memoir' )

    # prepend a seperator only if the file exists ( there are entries already in there )
    if os.path.exists( memoir_path ):
        lines.insert( 0, '--------------------\n' )

    with open( memoir_path, 'a' ) as f:
        f.writelines( lines )

我的代码,我不知道在哪里粘贴(如果它是正确的):

# read memoir file
if str(sys.argv) == ("r"):
    os.system('cat ~/.memoir')

# clear memoir file
if str(sys.argv) == ("c"):
    os.system('> ~/.memoir')

编辑:

由于答案,我做了一些改动,一切正常,但我想让这段代码更简单一些。这段代码的作者为我添加了一些usles功能,可以运行带有随机参数的程序,这些参数将被“转换”为注释中的空行。在我的更新之后似乎无论如何都没有用,所以我想摆脱这个功能。我认为它从第37行开始寻找#here !!!评论

新代码如下所示:

#!/usr/bin/env python3

import time
import os
import sys

def help():
    print ("memoir is a minimal cli diary")
    print ("run script with -r argument to read notes")
    print ("run script with -c argument to clear notes file")
    print ("run script with -h argument for help")

# add the current local time to the entry header
lines = [ time.asctime() + '\n' + '------------------------\n' + '\n' ]

if len(sys.argv) >= 2:
    if sys.argv[1] == '-r':
        # read .memoir file
        os.system('cat ~/.memoir')
        print('\n')
        exit(0)

    if sys.argv[1] == '-h':
        # print help
        help()
        exit(0)

    if sys.argv[1] == '-c':
        # clear .memoir file
        os.system('> ~/.memoir')
        exit(0)

    else:
        print("invalid argument, type m -h for help")
        exit(0)

if len(sys.argv) > 1 and len(sys.argv) != 2: #here!!!
    lines.append( ' '.join(sys.argv[ 1: ]))
    lines[-1] += '\n'
else:
    while 1:
        try:
            line = input()
        except EOFError:
            break

        # get more user input until an empty line
        if len( line ) == 0:
            break
        else:
            lines.append( line + '\n' )


# only write the entry if the user entered something
if len( lines ) > 1:
    memoir_path = os.path.expanduser( '~/.memoir' )

    # prepend a seperator only if the file exists ( there are entries already in there )
    if os.path.exists( memoir_path ):
        lines.insert(0, '\n------------------------\n')

    with open( memoir_path, 'a' ) as f:
        f.writelines( lines )

if len(sys.argv) >= 2:
    # clear .memoir file
    if sys.argv[1] == '-c':
        os.system('> ~/.memoir')

1 个答案:

答案 0 :(得分:0)

首先,sys.argv是一个数组,其中包含命令行的参数。所以你需要测试它的长度:

if len(sys.argv) >= 2 :
   #sys.argv[0] is the name of your program
   if sys.argv[1] == '-c' :

然后你可以看到文件写的是最新的行:

if len( lines ) > 1:
memoir_path = os.path.expanduser( '~/.memoir' )

# prepend a seperator only if the file exists ( there are entries already in there )
if os.path.exists( memoir_path ):
    lines.insert( 0, '--------------------\n' )

#here the file is opened with 'a' = append mode. 
#If you want to override the content of the file (for your command 'clear'), use 'w' = write mode.
with open( memoir_path, 'a' ) as f:
    f.writelines( lines )

所以你可以加入' clear'命令结束。 '阅读'命令宁愿在程序的开始处找到它的位置。