3

Python 的 os.system 默认无法识别 "**" 通配符

 7 months ago
source link: https://zhiqiang.org/coding/python-os-system-not-support-globstar.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python 的 os.system 默认无法识别 "**" 通配符

作者: 张志强

, 2023-09-13

, 共 910 字 , 共阅读 55 次

在 Python 里,我们可以直接用 os.system 来执行系统命令(假设下面的 strip 是一个可以处理多个文件的第三者程序):

os.system("strip ./*.csv")

上面的例子里,它还支持通配符,将处理当前目录下所有的 csv 文件。如果写下面这个(正式名字叫做 globalstar ),预期它能处理当前目录以及所有子目录下所有的 csv 文件,我们会发现它并没有效果:

os.system("strip ./**/*.csv")

而我们直接在命令行执行strip ./**/*.csv却能达到效果。这说明os.system支持了 shell 环境的展开,但并没有完整地支持。更深层次的原因是默认的 sh 默认不支持双星号通配符展开,但 zsh 等更现代的 shell 默认支持。对于 bash shell ,我们可以通过修改系统参数来让它支持"**"(这不足以解决上面的问题,因为 os.system 默认使用的是 sh ):

shopt -s globstar

我们只能用glob.glob 来替代:

import glob

files = glob.glob("./**/*.csv", recursive=True)
os.system("strip " + " ".join(files))

题外话: os.system 的运行环境

下面代码可以得到 os.system 默认的 shell 环境是 sh (注意它并不是当前的$SHELL 变量):

import os
os.system("echo $0")      # sh
os.system("echo $SHELL")  # /bin/zsh

所以修改$SHELL 变量是没有用的。要想明确使用的环境,需要直接指定:

import os  
os.system("/bin/zsh -c 'your_command'")

Q. E. D.

avatar-0.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK