将命令提示符数据分配给python变量

时间:2019-05-14 07:41:49

标签: python command-prompt

我正在尝试在Subversion存储库中检索文件的svn日志信息,以后需要将其转储为CSV。

显然,我使用python os package运行以下命令

代码:

filePath = r"C:\Project_Files\My_Project\file1.c" # My_Project is in Subversion
svn_command = "svn log " + filePath + "-v > C:\\information.txt"
os.system(svn_command)

我在information.txt中获取了svn日志数据,但是对多个文件(写入txt和从txt读取)执行这种操作非常耗时。

是否可以将从svn log -v获得的数据自动分配到python变量中?

1 个答案:

答案 0 :(得分:1)

您可以为此使用subprocess.Popen,请注意,我正在将命令拆分为一个列表,您可以预先创建该列表

import subprocess

filePath = r"C:\Project_Files\My_Project\file1.c" # My_Project is in Subversion
svn_command = "svn log " + filePath + "-v > C:\\information.txt"

#Split command into individual words
cmd_list = svn_command.split()

#Run command via subprocess Popen
cmd_output = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

#Get output and error 
cmd_output, cmd_err = cmd_output.communicate()

#Get output and error string
cmd_output_str = cmd_output.decode('utf-8', errors='ignore').strip()
cmd_err_str = cmd_err.decode('utf-8', errors='ignore').strip()

一个工作示例将是

import subprocess

cmd = 'uname -a'

#Split command into individual words
cmd_list = cmd.split()

#Run command via subprocess Popen
cmd_output = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

#Get output and error
cmd_output, cmd_err = cmd_output.communicate()

#Get output and error string
cmd_output_str = cmd_output.decode('utf-8', errors='ignore').strip()
cmd_err_str = cmd_err.decode('utf-8', errors='ignore').strip()

print(cmd_output_str)
print(cmd_err_str)

这里的输出将是

Darwin LUSC02WK0GKHTDH 18.5.0 Darwin Kernel Version 18.5.0: Mon Mar 11 20:40:32 PDT 2019; root:xnu-4903.251.3~3/RELEASE_X86_64 x86_64