子进程模块提供新行字符

时间:2015-06-01 18:16:16

标签: python python-3.x subprocess

我正在编写一个使用子进程模块运行net time \\server windows命令的脚本,并使用正则表达式解析该输出。

import datetime
import subprocess
import re

myDate = datetime.datetime.now().strftime("%y-%m-%d")
myTime = datetime.datetime.now().strftime("%H:%M")
myDateTime = datetime.datetime.now().strftime("%y-%m-%d %H:%M")

results_file = 'C:\\temp\\ServerTimes_{0}.txt'.format(myDate)
servers_central = 'C:\\temp\\DMS-CENTRAL.txt'
sql_central = 'gt2-dms1cst'

def find_server_time(string):
    """
    Search for a time in HH:MM:SS format from a string. Needs re module.

    "string" is the string of text to be searched.
    """
    re1 = '.*?'  # Non-greedy match on filler
    re2 = '(?si)Local time.*?(\d{2}:\d{2}:\d{2}\s+[AP]M)'

    rg = re.compile(re1+re2, re.IGNORECASE | re.DOTALL)
    m = rg.search(string.decode())
    if m:
        time1 = m.group(1)
        print("("+time1+")"+"\n")

def capture_time(server):
    server_time_output = find_server_time(subprocess.check_output(r'net time \\{0}'.format(server)))
    return server_time_output

def time_diff(sql_time, server_time):
    """
    "sql_time" is the time reported by the SQL server. Different for each zone.
    "server_time" is the time reported by each individual server."
    """
    diff = sql_time - server_time
    diff_mins = diff / datetime.timedelta(minutes=1)
    return diff_mins

def main():
    STWrite = open(results_file, "w+")
    STWrite.write("Server Times - " + myDateTime + '\n')
    STWrite.write('\n')
    sql_cst = capture_time(sql_central)
    print(sql_cst)
    STWrite.write("SQL Server time is {0}. All comparisons will be based on this.\n".format(sql_cst))
    server_list = open(servers_central)
    for line in server_list:
        line_time = capture_time(line)
        line_diff = time_diff(sql_cst, line)
        STWrite.write("{0} time is {1}. Time Difference of {2} from SQL.\n".format(line, line_time, line_diff))


if __name__ == "__main__":
    main()

我似乎遇到了一个问题,即Python将新行字符\ n提供给net time命令,这会导致错误。调试器显示:

(<class 'subprocess.CalledProcessError'>, CalledProcessError(1, 'net time \\\\gt2-dmcom1cst\n'), None)

如何才能正确格式化这个格式以进入子进程调用?

1 个答案:

答案 0 :(得分:2)

我怀疑问题出在这一行:

server_time_output = find_server_time(subprocess.check_output(r'net time \\{0}'.format(server)))

将rstrip()附加到变量,以删除末尾的任何空格:

server_time_output = find_server_time(subprocess.check_output(r'net time \\{0}'.format(server.rstrip())))

Althouth服务器[: - 1]也可以工作,如果输入的服务器变量没有换行符,它将剥离最后一个字符而不管它是什么(即“servername”将成为“servernam” )