我已经用 Python 玩了将近五天了,老实说我很喜欢它。
我有这个挑战,我无法解决它。
挑战是每 10 秒重复一次 top 命令的输出并将其保存到文件中。
这是我到目前为止所做的。
import time, os, threading
def repeat():
print(time.ctime())
threading.Timer(10, repeat).start()
f = open('ss.txt', 'w')
top = os.system("sudo top -p 2948")
s = str(top)
text = f.write(s)
print(text)
repeat()
Run Code Online (Sandbox Code Playgroud)
这里的主要问题是对 的调用top不会立即终止,而是在循环中连续运行以显示新数据。您可以通过指定-n1选项(-n允许您指定迭代次数)来更改此行为。
尝试这样的事情:
import subprocess
## use the following where appropriate within your loop
with open("ss.txt", "w") as outfile:
subprocess.call("top -n1 -p 2948", shell=True, stdout=outfile)
Run Code Online (Sandbox Code Playgroud)
Spa*_*kMe -1
首先,您的代码格式不正确,它应该看起来更像这样:
import time, os, threading
def repeat():
print(time.ctime())
threading.Timer(10, repeat).start()
f= open('ss.txt', 'w')
top= os.system("sudo top -p 2948")
s=str(top)
text = f.write(s)
print text
repeat()
Run Code Online (Sandbox Code Playgroud)
然后,您可能想研究一下 subprocess 模块 - 它是比 os.system 更现代、更犹太的调用外部命令的方式。但是,如果您的代码有效,那么实际问题是什么?