PythonforX循环多次返回

PythonforX循环多次返回,python,subprocess,Python,Subprocess,这里非常环保,只需编写代码片段来学习python 我将以下内容放在一起,以了解如何处理命令返回 test.py import subprocess proc = subprocess.Popen('date', stdout=subprocess.PIPE) output = proc.stdout.read() for x in output: print output 我运行这个,它迭代了58次: python test.py | wc -l 58 为什么,我不明白为什么

这里非常环保,只需编写代码片段来学习python

我将以下内容放在一起,以了解如何处理命令返回

test.py

import subprocess
proc = subprocess.Popen('date', stdout=subprocess.PIPE)
output = proc.stdout.read()
for x in output:
        print output
我运行这个,它迭代了58次:

python test.py | wc -l
58
为什么,我不明白为什么?我原以为它只返回1,这就是输出变量中的全部内容

p、 我知道有一些python库可以用来获取系统时间/日期,但这更多是关于我学习python语句和子流程

编辑:我应该添加,即使没有“wc-l”,它仍然会从date命令返回58个完整返回

编辑:如果我将“date”替换为“ls”,它会完整地运行“ls”命令两次


编辑:另一个例子,如果我使用“whoami”,它会返回我的用户名七次

output
是一个字符串(或者在Python 3中是一个bytestring)。迭代字符串/bytestring将迭代单个字符。尝试打印x,查看实际迭代的内容

您正在为
输出中的每个字符打印所有
输出
。字符串以
'\n'
结尾,因此字符串中的29个字符每一个都有两行输出。这就是58的来源

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> proc = subprocess.Popen('date', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> for x in output:
...         print output
... 
Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

Thu Jul 16 16:28:33 BST 2015

>>> 

试着单独运行
python test.py
:P.它没有运行58次。输出只是一个58个字符的字符串,for循环为每个字符打印一次输出。您可能需要区分
print
ing和
return
ing。每次函数调用只能
从函数(以及函数内部的循环)返回一次
对于输出中的x:print output
=>“对于输出中的每个字符,打印输出”如果没有“wc-l”,它仍然会为输出中的x返回58个日期“Thu 16 Jul 17:19:43 BST 2015”
:print output
->
print output
?不,它会添加一个完整的新日期行58次“Thu 16 Jul 17:19:43 BST 2015”
。不,它只打印29次日期,其中有29行空白。不使用
wc-l
试试。正如邓肯所解释的,流程是针对2015年7月16日星期四17:19:43英国夏令时中的“T”,打印2015年7月16日星期四17:19:43英国夏令时中的“h”,打印2015年7月16日星期四17:19:43英国夏令时中的“h”,以此类推。您正在打印输出,而不是x,因此您多次获得整个日期。现在就有意义了。我想我需要重新思考我是如何做到这一点的。