【问题标题】:Capture output from external command and write it to a file从外部命令捕获输出并将其写入文件
【发布时间】:2016-12-30 13:39:31
【问题描述】:

我正在尝试创建一个脚本,该脚本从我的 Ubuntu 服务器调用 linux 命令并将上述命令的输出打印到 txt 文件。这实际上是我写过的第一个脚本,我最近才开始学习 python。我想要 3 个单独文件夹中的 3 个文件,它们的文件名是迄今为止唯一的。

def swo():
        from subprocess import call
        call("svn info svn://url")

def tco():
        from subprocess import call
        call("svn info svn://url2")

def fco():
        from subprocess import call
        call("url3")

import time
timestr = time.strftime("%Y%m%d")

fs = "/path/1/" + timestr
ft = "/path/2/" + timestr
fc = "/path/3/" + timestr


f1 = open(fs + '.txt', 'w')
f1.write(swo)
f1.close()

f2 = open(ft + '.txt', 'w')
f2.write(tco)
f2.close()

f3 = open(fc + '.txt' 'w')
f3.write(fco)
f3.close()

它在 f.write() 函数上失败了。我一直坚持让 linux 命令的输出成为新文件中的实际文本。

【问题讨论】:

  • subprocess 可以通过将打开的文件对象传递给call 函数的stdout 参数,将命令输出直接写入文件。 docs.python.org/2/library/subprocess.html
  • 您可能希望从处理Python tutorial 开始。您的函数都没有返回(有用的)值,而且您一开始也没有调用它们。 (tco(),不是tco)。
  • 这就是为什么我在这里,火刑考验。

标签: python linux ubuntu svn scripting


【解决方案1】:

毕竟我想通了。以下效果很好!

## This will get the last revision number overall in repository ##

import os
sfo = os.popen("svn info svn://url1 | grep Revision")
sfo_output = sfo.read()
tco = os.popen("svn info svn://url2 | grep Revision")
tco_output = tco.read()
fco = os.popen("svn://url3 | grep Revision")
fco_output = fco.read()




## This part imports the time function, and creates a variable that will be the ##
## save path of the new file which is than output in the f1, f2 and f3 sections ##

import time
timestr = time.strftime("%Y%m%d")

fs = "/root/path/" + timestr
ft = "/root/path/" + timestr
fc = "/root/path/" + timestr

f1 = open(fs + '-code-rev.txt', 'w')
f1.write(sfo_output)
f1.close()

f2 = open(ft + '-code-rev.txt', 'w')
f2.write(tco_output)
f2.close()

f3 = open(fc + '-code-rev.txt', 'w')
f3.write(fco_output)
f3.close()

【讨论】:

    【解决方案2】:

    您可以这样做:

    import time
    import subprocess as sp
    timestr = time.strftime("%Y%m%d")
    
    fs = "/path/1/" + timestr
    ft = "/path/2/" + timestr
    fc = "/path/3/" + timestr
    
    
    f1 = open(fs + '.txt', 'w')
    rc = sp.call("svn info svn://url", stdout=f1, stderr=sp.STDOUT)
    f1.close()
    
    f2 = open(ft + '.txt', 'w')
    rc = sp.call("svn info svn://url2", stdout=f2, stderr=sp.STDOUT)
    f2.close()
    
    f3 = open(fc + '.txt' 'w')
    rc = sp.call("svn info svn://url3", stdout=f3, stderr=sp.STDOUT)
    f3.close()
    

    假设您使用的url3 命令应该是svn info svn://url3。这允许subprocess.call 将命令输出直接保存到文件中。

    【讨论】:

      猜你喜欢
      • 2015-07-09
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      相关资源
      最近更新 更多