1

I made a remote-control client which can receive commands from the server. The commands that are received will be executed as normal cmd commands in a shell. But how can I execute these commands in the background so that the user wont see any in- or output.


For example when I do this, the user would see anything whats going on:

import os
os.system(command_from_server)

2 Answers2

1

You can using subprocess Popen to start a cmd without waiting for end:

from subprocess import Popen
pid = Popen(["ls", "-l"]).pid

Popen has a lot of configure options for handling stdout and stderr. See the ufficial doc.

hussic
  • 1,816
  • 9
  • 10
0

To execute a command in background, you have to use the subprocess module.
For example:

import subprocess
subprocess.Popen("command", shell=True)

If you want to execute command with more than one argument eg: ls -a, the code is a bit different:

import subprocess
subprocess.Popen("ls -a", shell=True)

To change the directory you can use the os module:

import os
os.chdir(path)

But, as mentioned from tripleee in the comments bellow, you can also pass the cwd parameter to the subprocess.Popen-Method.

  • Thats not true; `subprocess` accepts a keyword argument `cwd=` where you can specify in which directory to run the subprocess. – tripleee Jun 13 '21 at 13:37
  • Also, `shell=True` is wrong in the second example; you *either* pass `ls -l` as a single string, or (better. here) drop the `shell=True`. – tripleee Jun 13 '21 at 13:38