如何在Python中传递任意参数

如何在Python中传递任意参数,python,arguments,command-line-arguments,argparse,Python,Arguments,Command Line Arguments,Argparse,在我必须完成的任务中,我应该创建一个替代“rm”命令的选项。我必须传递数量可变的参数,比如 $ rm.py /path/to/some/file ./somefile someotherfile $ rm.py /path/to/some/file ./somefile someotherfile -r $ rm.py -r /path/to/some/file ./somefile someotherfile $ rm.py *.java -r参数可以在任何位置作为任何参数传递。 使用常规“

在我必须完成的任务中,我应该创建一个替代“rm”命令的选项。我必须传递数量可变的参数,比如

$ rm.py /path/to/some/file ./somefile someotherfile
$ rm.py /path/to/some/file ./somefile someotherfile -r
$ rm.py -r /path/to/some/file ./somefile someotherfile
$ rm.py *.java
-r参数可以在任何位置作为任何参数传递。 使用常规“rm”命令时,-r的含义与中的相同。 它递归地删除目录及其内容

它运行脚本,不管给定的路径是什么

rm.py /path/to/some/file
然后将其移动到输出目录“~/rm\u trash” 如果有重复的,我也担心

但首先,我在理解如何处理这个问题上遇到了一些困难。 我是否应该在for循环中进行,如果其中一个参数等于'-r',从那里开始

我应该导入并使用argparse吗

我还有一些问题,但我想先处理一下我上面提出的问题


不得不再次发布,我仍然不明白如何获得除“r”之外的任何数量的参数的特定参数。我将使用argparse,因为您可以指定无序操作:


如果您不想使用
argparse
,或者无法用于赋值,您可以查看以下内容:


定义用于查找'-r'字符串的解析函数:

def parse(alist, astr='-r'):
    try:
        idx = alist.index(astr)
        r = alist.pop(idx)
        return True, alist
    except ValueError:
        return False, alist
如果我们这样做

import sys
r, rest = parse(sys.argv[1:])
应给出
r
的真/假值,以及文件名列表。在代码的其余部分使用这些

测试:

In [326]: list1 = 'rm.py /path/to/some/file ./somefile someotherfile'.split()   
In [329]: r, rest = parse(list1[1:])                                            
In [330]: r, rest                                                               
Out[330]: (False, ['/path/to/some/file', './somefile', 'someotherfile'])

In [331]: list2 = 'rm.py /path/to/some/file ./somefile someotherfile -r'.split()                                                                     
In [332]: r, rest = parse(list2[1:])                                            
In [333]: r, rest                                                               
Out[333]: (True, ['/path/to/some/file', './somefile', 'someotherfile'])
要说明出现'-r'时会发生什么情况,请执行以下操作:

In [335]: list2.index('-r')                                                     
Out[335]: 4
In [336]: list2.pop(4)                                                          
Out[336]: '-r'
In [337]: list2                                                                 
Out[337]: ['rm.py', '/path/to/some/file', './somefile', 'someotherfile']
如果它不存在,我们会得到一个
值错误

In [338]: list1.index('-r')                                                     
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-338-807fbe60be44> in <module>
----> 1 list1.index('-r')

ValueError: '-r' is not in list
使用
args=parser.parse_args()
读取
sys.argv

结果是一个
命名空间
对象,该对象具有所需的属性:

In [344]: args                                                                  
Out[344]: Namespace(r=False, rest=['/path/to/some/file', './somefile', 'someotherfile'])
In [345]: args.r                                                                
Out[345]: False
In [346]: args.rest                                                             
Out[346]: ['/path/to/some/file', './somefile', 'someotherfile']
使用
args.r
args.rest
的方法与上面的
r
rest
相同

'-r'可以在文件名列表之前或之后<代码>argparse在需要定义更多选项(如“-r”)时变得更有用。它还负责显示帮助消息和有意义的错误

In [347]: parser.parse_args(['--help'])                                         
usage: ipython3 [-h] [-r] [rest [rest ...]]

positional arguments:
  rest        file names

optional arguments:
  -h, --help  show this help message and exit
  -r          recursive flag
为什么不使用:

os.system( 'rm ' + ' '.join( sys.argv[1:] )

当前代码现在如何检查参数?您是在检查
sys.argv
(出于教学原因)的元素,还是在使用参数解析库?我之前发布了这篇文章,并被告知要查看argparse库,我确实认为有一些帮助。但我不知道我是否正确使用了它,也不知道我是否能在作业中使用它。一位同行告诉我,首先要在foor循环中查找'-r'参数。但是怎么做?到目前为止你试过什么?发布一些现有代码将有助于提供更好的答案。此外,StackOverflow用户将无法确定在作业中使用
argparse
是否是一个好主意。可能是@NicholasM的重复。是的,我知道,嗯,目前我没有任何代码,只是psuedo,我不知道是否可以发布。是的,可能的重复是我关闭的帖子,当它关闭时没有帮助我。即使我不使用“-r”命令,argparse应该工作吗?或者,如果我只调用一个参数、两个参数或三个参数,等等?只要它是可选参数,它只会在您指定它时使用它。argparse非常强大,它应该能够处理您的所有案例。这是howto文档:谢谢,让我继续阅读。其他参数呢,比如,如果是文件、目录、/path/to/filethank,让我试试这种情况,其他路径呢,如果我想使用shutil移动文件/目录,我需要一个源代码,我应该能够操作您上面发布的代码,对吗?
In [347]: parser.parse_args(['--help'])                                         
usage: ipython3 [-h] [-r] [rest [rest ...]]

positional arguments:
  rest        file names

optional arguments:
  -h, --help  show this help message and exit
  -r          recursive flag
os.system( 'rm ' + ' '.join( sys.argv[1:] )