您的代碼應該按設計工作。無論出於何種原因,它將輸出發送到控制檯而不是變量。此代碼爲我工作在PowerShell的3.0
$python = & python -V
write-host "Python Version: " + $python
你甚至評論說,類似的命令按預期工作像下面提及。
$python = & ping -n 1 localhost
write-host "Python Version: $python"
雖然我不知道的根本原因,你可以寫一些代碼,這將迫使標準輸出捕獲到一個System.Diagnostics.Process
對象。我從另一個SO answer處取得代碼。
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "C:\Python34\python.exe"
$pinfo.Arguments = "-V"
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
Write-Host "Python Version: $stdout"
我不知道爲什麼一個簡單的兩個班輪不適合你。當你做這樣的事情時會發生什麼?再次,我沒有在我的路徑變量Python,所以我用我的例子中的文件的全名。
Write-Host "Python Version: $(&"C:\Python34\python.exe" -V)"
or
Write-Host "Python Version: $(& python.exe -V)"
我無法用'&ping -n 1 localhost'這樣簡單的東西來重現這一點。所以我實際上安裝了Python來進行測試以防萬一,而且你的代碼確實可行。我必須點源python.exe進行測試,但'$ python =&。\ python.exe -V'但輸出正常。我也在使用PowerShell 3.0。當你嘗試使用'$ python =&ping -n 1 localhost'和'write-host'時,會發生什麼?Python版本:$ python「'.FYI變量會在雙引號內部擴展。 – Matt 2014-09-19 13:30:09
謝謝@Matt。當我使用
$python = & ping -n 1 localhost
代碼時,我可以得到Python Version: Pinging AWSRIA185.one.ads.bms.com [::1] with 32 bytes of data: Reply from ::1: time<1ms Ping statistics for ::1: Packets: Sent = 1, Received = 1, Lost = 0 (0% loss), App roximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 0ms, Average = 0ms
的輸出。 – Mohan 2014-09-19 14:33:49如果我運行代碼
$python = &.\python.exe -V
,那麼我得到& : The term '.\python.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
– Mohan 2014-09-19 14:35:48