简体   繁体   English

Bash是否在我的python命令行参数中扩展了“ *”字符?

[英]Is Bash expanding the “*” character in my python command line parameter?

With the following command in bash : bash使用以下命令:

python myscript.py filename_pattern*

I got two different sys.argv in two Linux machines: 我在两台Linux机器上得到了两个不同的sys.argv

  • Machine A : sys.argv[1] = filename_pattern* 机器Asys.argv[1] = filename_pattern*
  • Machine B : sys.argv[1] = filename_pattern-2013-06-30 机器Bsys.argv[1] = filename_pattern-2013-06-30

Note : filename_pattern-2013-06-30 is a file in my current directory. 注意filename_pattern-2013-06-30是我当前目录中的文件。

One of my colleague tell me that's the evil of bash . 我的一位同事告诉我,那是bash But I check the bash in two machines are of the same version, and I checked ~/.bashrc , /etc/bashrc , /etc/profile.d/*.sh too. 但是我检查了两台机器上的bash的版本是否相同,我也检查了~/.bashrc/etc/bashrc/etc/bashrc . /etc/profile.d/*.sh

Can anyone point out how come the two same version bash act differently ? 谁能指出两个相同版本的bash如何表现不同?

It is because in one of your machine, in the folder, there in no file that could match the pattern. 这是因为在一台计算机上的文件夹中,没有文件可以匹配该模式。 So when this happens, the * remains. 因此,发生这种情况时, *仍然存在。 You can test with one computer, with and without a file match the pattern. 您可以在一台计算机上进行测试,无论文件是否匹配该模式。 There is another reason, the shell option nullglob is disabled. 还有另一个原因,shell选项nullglob被禁用。 You can read the GNU bash reference for this. 您可以阅读GNU bash参考

Why you see the different behavior on the two machines is either down to the files present in the directory on both machines or based on the shell options, as pointed out in the comments. 注释中指出,为什么在两台计算机上看到不同行为的原因取决于两台计算机上目录中存在的文件还是基于shell选项。

Either way, the way to avoid the problem is to simply surround the argument in quotes so that Bash treats it literally. 无论哪种方式,避免问题的方法都是将引数简单地括在引号中,以便Bash逐字对待它。

python myscript.py "filename_pattern*"

You could handle it in your python program like this example that I found in an introductory book on python. 您可以像我在python入门书中找到的示例一样在python程序中处理它。 Then it won't matter if bash expands it or not. 那么bash是否扩展它并不重要。

import glob
import sys

sys.argv = [item for arg in sys.argv for item in glob.glob(arg)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM