从bash命令行获取未扩展的参数 [英] Get unexpanded argument from bash command line

查看:66
本文介绍了从bash命令行获取未扩展的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从bash命令行将glob表达式作为参数传递给脚本时,它会被扩展,并且与之匹配的文件将被解压缩到 sys.argv

When passing a glob expression as an argument to a script from the bash command line, it gets expanded, and the files matching it are unpacked into sys.argv:

# stuff.py
import sys

print(sys.argv)



host:~$ python stuff.py a*
['stuff.py', 'a1', 'a2', 'a3']

我想将这些文件保存在容器中,作为 sys.argv 的单个元素:

I would like to get these files in an container, as a single element of sys.argv:

host:~$ python stuff.py a*
['stuff.py', ['a1', 'a2', 'a3']]






我知道将glob表达式放在引号中并使用 glob 模块可以解决问题:

import sys
import glob

print(glob.glob(sys.argv[1]))



host:~$ python stuff.py "a*"
['a1', 'a2', 'a3']

但是,这需要添加引号周围的引号,因此不能直接使用制表符完成。

However, this requires to add quotes around the arguments, so tab-completion cannot be used directly.

是否可以防止命令行参数被扩展?

Is it possible to prevent the command line arguments from being expanded?

推荐答案


从bash命令行获取未扩展的参数

Get unexpanded argument from bash command line

传递未经外壳扩展的参数的唯一方法是引用该参数或使用适当的转义符。
具体来说,要引用或转义shell尝试扩展的部分。

The only way to pass an argument unexpanded by the shell is to either quote it or to use appropriate escapes. Specifically, to quote or escape the portions that the shell would try to expand.


但是,这需要在引号周围加上引号。这些参数,因此不能直接使用制表符补全。

However, this requires to add quotes around the arguments, so tab-completion cannot be used directly.

您无需在整个参数周围添加引号。
足以解决外壳中具有特殊含义的字符。

You don't need to add quotes around entire arguments. It's enough to do that around characters that have special meaning in the shell.

例如,如果您自动完成此命令行直到这一点:

For example, if you autocomplete this command line until this point:

python stuff.py file_00
                       ^ cursor is here, and you have many files,
                         for example file_001, file_002, ...

此时,如果要添加文字 * file_00 * 传递给Python脚本而无需外壳程序对其解释,
您可以这样编写:

At this point, if you want to add a literal * to pass file_00* to the Python script without the shell interpreting it, you can write like this:

python stuff.py file_00\*

或类似这样:

python stuff.py file_00'*'

再举一个例子,
注意,当文件模式包含空格时,
制表符将添加 \ 正确,例如:

As a further example, note that when the file pattern contains spaces, tab completion will add the \ correctly, for example:

python stuff.py file\ with\ spaces\ 00

在这里,您也可以照常添加转义的 *

Here too, you can add the escaped * as usual:

python stuff.py file\ with\ spaces\ 00\*

最后,
自然可以使用制表符补全,
并在制表符补全后仅转义特殊字符
,然后使用 glob Python模块扩展参数中的glob部分。

In conclusion, you can use tab completion naturally, and escape only the special characters after the tab completion. And then use the glob Python module to expand the glob parts in arguments.

这篇关于从bash命令行获取未扩展的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆