将文件名作为参数传递的PowerShell通配符



我正在使用PowerShell在Windows机器上运行Python 3。我正在尝试执行一个 Python 文件,然后使用通配符传递许多文件(file1.html、file2.html 等(作为参数。我可以让它工作,执行如下几个步骤:

PS $files = Get-Item .file*.html
PS python mypythonfile.py $files

我的问题是,是否可以在不必使用Get-Item并将结果分配给变量的情况下完成此操作?我尝试像这样运行相同的文件python mypythonfile.py .file*.html但这会导致 Python 解释器出错,因为 PowerShell 不会解析通配符并使用通配符传递字符串。

您似乎在交互式控制台中。你不需要将get-item的结果分配给一个变量,如果这就是你想要实现的全部。试试这个:

python mypythonfile.py (get-item .file*.html)

尽管这将起作用,但实际上您应该使用 .由 get-item 生成的结果对象的 FullName 属性:

python mypythonfile.py (get-item .file*.html).FullName

虽然Windows shell(即PowerShell和CMD(确实支持glob模式,但它们本身并不扩展模式(与Unix shell不同(。相反,应该支持通配的命令必须自己实现通配符扩展。

Python 为此提供了glob模块:

import sys
import glob
for arg in glob.glob(sys.args[1]):
    print(arg)

这允许您的脚本在调用时处理带有通配符的参数,例如:

python script.py .file*.html

否则,需要使用 PowerShell cmdlet,该 cmdlet 为你扩展通配符模式并返回路径列表,例如 Get-ChildItem .要么在变量中收集列表:

$files = Get-ChildItem .file*.html | Select-Object -Expand FullName
python script.py $files

或在表达式中运行 PowerShell 语句:

python script.py (Get-ChildItem .file*.html | Select-Object -Expand FullName)

或者你可以让你的Python脚本从stdin

import fileinput
for line in fileinput.input():
    print(line.replace('n',''))

并将文件列表通过管道连接到脚本中:

Get-ChildItem .file*.html | Select-Object -Expand FullName | python script.py

执行一个$files | get-Member以查看Get-Item不返回字符串,而是返回包含多个条目的System.IO.FileInfo对象。
如果文件名中没有空格,这可以执行以下操作:

 $files = (Get-Item .file*.html) -join(' ')

否则

$files =  '"'+((Get-Item .file*.html) -join('" "'))+'"'

最新更新