[英]PowerShell Python command-line arguments
I'm trying to run a Python script in PowerShell. 我正在尝试在PowerShell中运行Python脚本。 While using
sys
module I stumble upon a problem of getting the return value of a PowerShell function. 在使用
sys
模块时,我偶然发现了获取PowerShell函数的返回值的问题。 The function in question is Date -f 'dd\\/MM\\/yyyy'
that returns 14/03/2019
and I'd like that value to be used as an argument in the Python script. 有问题的函数是
Date -f 'dd\\/MM\\/yyyy'
返回14/03/2019
,我希望将该值用作Python脚本中的参数。 I've been able so far to get the literal arguments from the command line, eg text
. 到目前为止,我已经能够从命令行获取文字参数,例如
text
。
If I understand correctly, you want to have the output of the command Date -f 'dd\\/MM\\/yyyy'
to be fed into your python script ( script.py
). 如果我理解正确,则希望将
Date -f 'dd\\/MM\\/yyyy'
命令的输出输入到python脚本( script.py
)中。
What you are looking for are so called "pipes" or output redirects. 您正在寻找的是所谓的“管道”或输出重定向。 Looking at the officical documentation ( https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-output?view=powershell-6 ) the following might work:
查看官方文档( https://docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.utility/write-output?view=powershell-6 ),以下方法可能会起作用:
$DATE=Date -f 'dd/\MM\/yyyy'
Write-Output $DATE | python script.py
This Python script (see sys.argv
docs ): 此Python脚本(请参阅
sys.argv
docs ):
import sys
print(sys.argv)
called like this in Powershell: 在Powershell中这样调用:
python .\test.py -date $(Date -f "dd\/MM\/yyyy")
outputs: 输出:
['.\\test.py', '-date', '14/03/2019']
On a general note, I recommend using better date formats than dd/MM/yyyy
- ISO 8061 yyyy-MM-dd
would be a good one. 一般而言,我建议使用比
dd/MM/yyyy
更好的日期格式-ISO 8061 yyyy-MM-dd
将是一个很好的日期格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.