简体   繁体   中英

Python script reading terminal every period of time

I need to create script that do a few things:

  1. Pass a command to the Linux shell, that starts a process.
  2. Read every (for example) 1s the terminal conent, and clear terminal to get only the new lines.
  3. Close the process and the terminal.

I tried to emulate this, by simplifying the task by just writing a command and reading it two times, but it does not seem to work. Do you have any idea how to solve this problem? Is it possible to do this this way or maybe is there more clever way to handle it?

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')

I think you should do something like the code shown below:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM