开发者

Putting "Ctrl-A" in Python shell script

I'm trying to write a shell scr开发者_如何学Pythonipt in Python to automate a process, but one of the commands I have to use is Ctrl+A (I'm using screen). Is there a way to code this into the script?


No. You won't be able to control screen program with a python program/script running within it.


In a bash script I can do something like:

if [-n "$STY"]; then
    screen -X command
fi

That is screen sets $STY, see if it is set to determine if you are in screen. Then send the command that you want using -X flag of screen. You can easily do the same in Python.

Actually, it seems like screen -X command just errors silently if not in screen, so you can even use it without checking for the $STY

Gnu-Screen: Run script that sends commands to the screen session it is being run in


The Python curses module could help you out some. :)


Ok, this is going to be tricky. As Pablo Santa Cruz commenting, your script is running within the screen session, so it's normal stdin/stdout/stderr interface with the world isn't going to work, since screen isn't listening for Ctrl-A on any of those handles.

But all is not lost. Screen is listening for Ctrl-A on it's stdin, which is how your keyboard's Ctrl-A is reaching you. (The following assumes Linux, but I'm pretty sure other Unices have something similar...) First, your script will need to figure out the pid of it's parent screen session (the psutil library may help). Then, you'll find the /proc/{pid}/fd directory contains files corresponding to the filenos of all filehandles that process has open. For normal unix processes, '0' is stdin, '1' is stdout, '2' is stderr. Assuming proper user permissions, your script should be able to open /proc/{pid}/fd/0 and write Ctrl-A to the file, simulating the user pressing the key.

I'm not exactly sure if this will work, never tried it before, but if you have to command screen from a subprocess, some variant of that is probably going to be your best bet.


The ASCII code for CTRL_A is 1. So the following python code will work.

    CTRL_A = chr(1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜