2014-09-19 64 views
1

在我的powershell腳本中,我試圖在Windows Server 2008中獲得python版本。此腳本僅在控制檯中打印版本,但我沒有將值變爲變量。在Windows Server 2008中從powershell 3.0腳本獲取python版本

代碼:

$python = & python -V 
write-host "Python Version: " + $python 

預期輸出:

Python Version: Python 2.7.8 

實際輸出:

Python 2.7.8 
Python Version: 

任何一個可以幫助我出去了。

+1

我無法用'&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

+0

謝謝@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

+0

如果我運行代碼$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

回答

2

python.exe -V將版本信息寫入錯誤輸出流而不是成功輸出流。由於在運行Write-Host之前打印了「錯誤」消息,並且第一個命令在成功輸出流上沒有輸出將被分配到$python,因此在Write-Host語句中使用該變量時爲空,您將得到觀察到的輸出。

改變這一行:

$python = & python -V 

這樣:

$python = & python -V 2>&1 

,問題就會消失。

+0

謝謝@Ansgar。這工作。 – Mohan 2014-09-19 15:40:01

+0

我想知道如果較新版本的python改變了這一點,因爲我沒有他的問題與Python 3.1.4 – Matt 2014-09-19 15:47:09

+0

@Matt可能。我使用Python 3.3.2進行了測試。 – 2014-09-19 15:54:31

0

您的代碼應該按設計工作。無論出於何種原因,它將輸出發送到控制檯而不是變量。此代碼爲我工作在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)" 
+0

'$ python =&python -V 2>編碼爲'$ puthon =&。\ python.exe -V write-host'的代碼爲' – Mohan 2014-09-19 15:42:55