简体   繁体   English

Python:在脚本中处理globbing

[英]Python: Handle globbing within a script

$ script.py *.txt

I want to run script.py on all .txt files in this directory, which include 1.txt, 2.txt, and 3.txt. 我想在此目录中的所有.txt文件上运行script.py,其中包括1.txt,2.txt和3.txt。 There's two approaches I can think of to this: having the python script handle globbing, or having the shell spawn multiple processes. 我可以想到两种方法:让python脚本处理globbing,或让shell产生多个进程。

Having the script handle globbing is the approach I prefer. 让脚本处理通配是我更喜欢的方法。

According to Prevent globbing after variable substitution I can use set -f to turn it off. 根据变量替换后防止globbing,我可以使用set -f将其关闭。 How would I be able to specify this option exclusively for Python scripts? 我如何能够专门为Python脚本指定此选项?

Why would you want to do this via Python globbing? 你为什么要通过Python globbing来做这个? A shell script would be perfect, IMHO, and you separate the core functionality of what your python script is supposed to do, vs. the menial task of running it for all the *.txt files in the directory. 一个shell脚本是完美的,恕我直言,你分开你的python脚本应该做的核心功能,以及为目录中的所有*.txt文件运行它的琐碎任务。

If for some reason you need the gobbling inside the script (counting the total number of files processed, for example), it's possible to use: 如果由于某种原因你需要在脚本内部进行吞噬(例如,计算处理的文件总数),则可以使用:

script.py '*.txt'

or 要么

script.py "*.txt"

If you have a huge number of files in the directory, iglob() would be better. 如果目录中有大量文件, iglob()会更好。 You have to pass in the glob parameter as a string: 您必须将glob参数作为字符串传递:

$ script.py "*.txt"

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

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