Hayat
Hayat

Reputation: 1639

How to run python file inside tmux session?

I am trying to run python script inside tmux session. I wrote a command (tmux new-session -d -s my_session) which is running fine from crontab.

But when I am trying to run python or shell file with tmux new-session -d -s my_session 'python3 test.py or tmux new-session -d -s my_session 'sh test.sh The script doesn't run. I used the reference from here. Please help me with this.

Upvotes: 4

Views: 14332

Answers (1)

pfmaggi
pfmaggi

Reputation: 6476

Edit
You can separate tmux commands with \;, then use the send-keys command to send the command to the active window.
In your case you can use:

tmux new-session -d -s my_session \; send-keys "python3 test.py" Enter
tmux new-session -d -s my_session \; send-keys "sh test.sh" Enter
tmux new-session -d -s my_session \; send-keys "python3 -m http.server 8080" Enter

You can find more about send-keys options on the tmux manpages section for send-keys:

send-keys [-lMRX] [-N repeat-count] [-t target-pane] key ...
(alias: send)
Send a key or keys to a window. Each argument key is the name of the key (such as ‘C-a’ or ‘NPage’) to send; if the string is not recognised as a key, it is sent as a series of characters. The -l flag disables key name lookup and sends the keys literally. All arguments are sent sequentially from first to last. The -R flag causes the terminal state to be reset.

-M passes through a mouse event (only valid if bound to a mouse key binding, see MOUSE SUPPORT).
-X is used to send a command into copy mode - see the WINDOWS AND PANES section.
-N specifies a repeat count.

The send-keys syntax is described on the Key Bindings section of the tmux manpage. The key names used by send-keys are the same ones used by bind-key.

I usually work with different configuration files, on top of a base file.

Imagine that you've your tmux configuration in ~/.tmux.conf I then create different configuration files in my ~/.tmux/ folder. As an example I can have a python configuration file (use the attach if you want to enter in the session):

# To use this configuration launch tmux with the command:
#   > tmux -f ~/.tmux/python.conf attach
#

# Load default tmux config
source-file ~/.tmux.conf

# Create session and launch python script
new-session -s python -n python -d -c ~/src/python/
send-keys "python test.py" Enter

This gives me the flexibility to create much more complex sessions.

Upvotes: 7

Related Questions