gpt4 book ai didi

python - 子进程模块提供换行符

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:25 25 4
gpt4 key购买 nike

我正在编写一个脚本,它使用子进程模块来运行 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)

我怎样才能正确地格式化它以提供给子进程调用?

最佳答案

我怀疑问题出在这一行:

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())))

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

关于python - 子进程模块提供换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30580414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com