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

Assigning command prompt data into a python variable

我正在尝试检索 subversion repository 中文件的 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变量?

你可以使用 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