为什么sys.stdin中的字符串与我脚本中的硬编码字符串不同?

时间:2015-08-19 15:55:54

标签: python python-3.x

为什么以下打印"错误"?

test.py:

Redraw

命令行:

Add-Type -Path 'C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll'
$server = new-object ("Microsoft.SQLServer.Management.Smo.Server")  "(Local)"    
$databases = $server.databases                              

## some variables definitions
$db1 = "Model"
$db2 = "TempDb"
$db3 = "Master"
$backupDirectory = "c:\Backup\Etc"
$table = @{}
## 

$array = @($db1,$db2,$db3,$db4,$db5,$db6,$db7,$db8,$db9,$db10,$db11)            

foreach ($element in $array) 
{
 foreach ($db in $databases) 
 {
    if($db.Name -like $element) 
    {
        $dbname = $db.Name
        $dateTime = get-date -format yyyy_MM_dd 
        $fullBackupFilePath = ($backupDirectory + "\" + $dbname + "_FULL_" + $dateTime + ".bak")   

        $table.Add(($db),($fullBackupFilePath))
    }
 }
}

$table | Format-Table 

1 个答案:

答案 0 :(得分:2)

因为sys.stdin文本带有换行符。当test.py是这样时更明显:

import sys

if __name__ == "__main__":
    for text in sys.stdin:
        text_in_script = 'test'

        print("Input:  {}".format(text))
        print("Script: {}".format(text_in_script))
        print(text == text_in_script)

解决方案是剥离换行符。以下将返回" True":

import sys

if __name__ == "__main__":
    for text in sys.stdin:
        text_in_script = 'test'

        # warning: rstrip() removes all whitespace; see rstrip() docs for alternatives
        print(text.rstrip() == text_in_script)