A ctrl-O is just a character, same as any other. You can send it by writing '\x0f'
(or, in Python 3, b'\x0f'
).
However, that probably isn't going to do you any good. Most programs that provide an interactive GUI in the terminal, like nano
, cannot be driven by stdin. They need to take control of the terminal, and to do that, they will either check that stdin isatty
and then tcsetattr
it, or just open /dev/tty
,
You can deal with this by creating a pseudo-terminal with os.openpty
, os.forkpty
, or pty
.
But it's often easier to use a library like pexpect
to deal with interactive programs, GUI or otherwise.
And it's even easier to not try to drive an interactive program in the first place. For example, unlike nano
, ed
is designed to be driven in "batch mode" by a script, and sed
even more so.
And it's even easier to not try to drive a program at all when you're trying to do something that can be just as easily done directly in Python. The easiest way to append something to a file is to open
it in 'a'
mode and write
to it. No need for an external program at all. For example:
new_line = input('What do you want to add?')
with open(fname, 'a') as f:
f.write(new_line)
If the only reason you were using nano
is because you needed something to sudo
… there's really no reason for that. You can sudo
anything else—like sed
, or another Python script—just as easily. Using nano
is just making things harder for yourself for absolutely no reason.
The big question here is: why do you have a file that's not writable by your Python script, but which you want arbitrary remote users to be able to append to? That sounds like a very bad system design. You make files non-writable because you want to restrict normal users from modifying them; if you want your Python script to be able to modify it on behalf of your remote users, why isn't it owned by the same user that the script runs as?