python for loop on subprocess.Popen() and os.system() i get TypeError: 'int' object is not iterable

python for loop on subprocess.Popen() and os.system() i get TypeError: 'int' object is not iterable

说我写了下面的代码:

import os
import subprocess

 for i in os.system('ls'):
    print i

我遇到以下错误:

 Traceback (most recent call last):
 File "<console>", line 1, in <module>
 TypeError: 'int' object is not iterable

当我尝试对 subprocess.Popen

做同样的事情时
 for i in subprocess.Popen("ls" , shell=True).wait():
    print i

我也有同样的问题。如果我只做 os.system('ls') 或 subprocess.Popen("ls" , shell=True).wait()

  db.sqlite3  ip  manage.py  mysite  
  0

输出后的额外“0”出现问题。有什么方法可以摆脱它吗?

如果你想要标准输出:

proc = subprocess.Popen("ls", shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
    print(line)

os.system() returns the return value(成功则为 0)。

由于显而易见的原因,您不能迭代整数,因此您必须获取可迭代的数据。

您想获取作为输出的字符串,对其进行解析并对其进行迭代。 subprocess.check_output() 函数应该是你的选择。