Python: 如何在使用已定义变量的同时 运行 命令?

Python: how to run a command while using a defined variable?

我是 Python 的初学者,我正在尝试列出定义为变量但无济于事的目录的内容。

这是代码:

#!/usr/bin/python
import os

location = "/home/itaig/testdir"
command = os.system('ls -l')," location"

我的目的是计算该位置的文件数量并打印数量。

如何实现?

编辑#1:

在 bash 中我会做 ls -l $location | wc -l ,在 Python 中等效于什么?

无论如何,我查看了评论中的链接,但无法使其正常工作...您能给我举个例子吗?

谢谢

您可以使用旧的 os.popen 函数:

p = os.popen('ls -l %s' % location)
nb_lines = 0
while p.readline():
  nb_lines += 1

您可以使用 os.listdir。 这是独立于平台的,因为 os 模块将处理低级工作

print len(os.listdir(location))