I want to make a python script that:
opens a file, executes the command i,
then writes 2 lines of code, hits escape
executes the command ZZ.
I was thinking along the lines of os.system("vi program") then os.system("i") and os.system("code"), but that didn't work because you can only execute commands. Thank you!
3 Answers
It's not clear why you want to do this. To truly run an interactive program, you'll have to create a pseudo-tty and manage it from your python script - not for the faint of heart.
If you just want to insert text into an existing file, you can do that directly from python, using the file commands. Or you could invoke a program like sed, the "stream editor", that is intended to do file editing in a scripted fashion. The sed command supports a lot of the ex command set (which is the same base command set that vi uses) so i, c, s, g, a, all work.
Comments
THE CODE
import pyautogui
from multiprocessing import Process
import os
vi_proc = Process(target = lambda: os.system("vi program"))
vi_proc.start()
pyautogui.typewrite("i")
pyautogui.typewrite("This code\n")
pyautogui.typewrite("really sucks!")
pyautogui.press("esc")
pyautogui.typewrite("ZZ")
vi_proc.join()
THE BLABLABLA
Well, I really not understand WHY, but I coded a working solution. I used PyAutoGUI, a really simple library that allow you to emulate key and mouse presses and movements.
You may also need to install some sysyem package, like libjpeg8-dev. Furthermore, probably you have also to issue the command xhost + temporarily before installation.
That said, in bash it will be simply:
echo -e "This code\nreally sucks!" > program
Comments
If you really want to run VIM from the command-line, you can use the VIM -c option. Something like this:
gvim -c "normal oFirst line" -c "normal oSecond line" -c "ZZ" foo.txt
(Adjust using o, O, i or I as according to where you want the line inserted).
There must be an easier way to insert two lines in a file, though.