簡體   English   中英

Python 腳本閱讀終端每段時間

[英]Python script reading terminal every period of time

我需要創建腳本來做一些事情:

  1. 將命令傳遞給 Linux shell,啟動一個進程。
  2. 每隔(例如)1s 讀取終端內容,並清除終端以僅獲取新行。
  3. 關閉進程和終端。

我試圖通過僅編寫一個命令並讀取兩次來簡化任務來模擬這一點,但它似乎不起作用。 你知道如何解決這個問題嗎? 是否有可能以這種方式執行此操作,或者是否有更聰明的方法來處理它?

from subprocess import Popen, PIPE, STDOUT
import pty
import os

master, slave = pty.openpty()
p = Popen('ls', shell=True, stdout=slave, stdin=PIPE, stderr=slave, close_fds=True)
stdin_handle = p.stdin
stdou_handle = os.fdopen(master)

stdin_handle.write('cd /')
stdin_handle.write('ls')
print stdout_handle.readline()

stdin_handle.write('clear')
stdin_handle.write('cd /home')
stdin_handle.write('ls')
print stdout_handle.readline()

stdin_handle.write('exit')

我認為您應該執行如下所示的代碼:

import os
import time

while True:
    start_time = time.time()
    # can check if you are in correct working directory: os.getcwd()

    os.chdir('/')
    os.listdir()

    print(f'\33c\e[3J')
    os.chdir('/home')
    os.listdir()

    print(f'\33c\e[3J')
    time.sleep(1 - ((time.time() - start_time) % 1))

    # exit due to some conditional for example: if datetime.now().hour == 9:
    exit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM