【问题标题】:What is printing this number after my python script executes我的python脚本执行后打印这个数字是什么
【发布时间】:2014-01-21 23:50:36
【问题描述】:

请原谅我问了一个简单的python问题。这是我第一次使用python。

我现在在 mac book pro 上编写这个脚本。稍后它可能会部署在 Centos 服务器上。脚本抓取获取文件作为参数。稍后我会处理输出。

#!/usr/bin/python
import sys
import subprocess

if len(sys.argv) < 2:
   print ("Not enough arguments")
   print ("Usage: " + sys.argv[0] + " log_file output_file")
   print ("i.e. " + sys.argv[0] + " stream.log output.csv")
   sys.exit(1)
else:
   input = open (sys.argv[1])
   output = open (sys.argv[2],'w')

proc = subprocess.Popen("cat " + input.name + " | cut -d ',' -f 3 | sort | uniq | wc -l", shell=True)

print "got here"
output.close()
print "got here22222"
input.close()

我只是从终端运行它并执行。但是,在它打印出最后一个

到这里22222

有几秒钟的延迟,然后它打印出 567。但是,我上面的脚本中没有打印 567。有谁知道为什么要打印这个号码?如何阻止它打印此号码?提前感谢您能给我的任何帮助。

./test.py a b
got here
got here22222
~/test$      567

【问题讨论】:

  • 我认为它来自对cat 的子流程调用。您正在(在管道中)处理文件,而 567 可能是该管道的结果

标签: python linux darwin


【解决方案1】:

要阻止这种情况发生,您可以使用 proc.wait() 等待子进程,否则我猜管道命令的输出是 567

【讨论】:

    【解决方案2】:

    管道的最后阶段是wc -l,它可能会生成数字567。到达该点需要几秒钟。

    【讨论】:

    • 我是个白痴。谢谢你。这是 wc -l。我还想出了如何将输出分配给变量。我需要放一个 stdout=subprocess.PIPE;例如新的 python cmd 应该是 proc = subprocess.Popen("cat " + input.name + " | cut -d ',' -f 3 | sort | uniq | wc -l", shell=True, stdout=subprocess.PIPE )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    相关资源
    最近更新 更多