How to execute arbitrary bash commands from python 3? for example: bash("ifconfig") . Maybe there is a library?

  • 3
    os.system ("ifconfig") - Fat-Zer
  • the same thing. thanks - Andrey Yurevich
  • @ Fat-Zer, just bash interpreter commands ( bg , fg , set etc., etc.), as far as I understand, cannot be done this way. I understand that the author of the question does not understand what the difference is between the programs and interpreter commands, but still ... - aleksandr barakin
  • @alexanderbarakin under the magic word bash, an ordinary user understands everything that is entered into the terminal. The built-in bash commands can be found by typing / bin / bash help. - Hellseher
  • 3
    @Hellseher, yes, I'm aware of the mess in the terminology (probably, it is present in varying degrees in any field of knowledge). but the very existence of him (the mess), it seems to me, cannot be a reason for his (the mess) aggravation. - aleksandr barakin

1 answer 1

To execute an executable file, you do not need to run bash at all. The operating system allows new child processes to be created without launching the shell.

In Python, you can use the subprocess module for this:

 import subprocess subprocess.run(['ip', 'addr']) 

If you need to execute a command that uses bash functionality. For example, to find lines common to two files using process replacement :

 subprocess.run('comm -12 <(sort -ua) <(sort -ub)', shell=True, executable='/bin/bash') 

if you do not specify executable , then the /bin/sh shell is used, which may not support bash-isms.

To redirect the output of the command, you can pass stdout, stderr parameters, or call the wrapper subprocess.check_output() . The presence of a check in the name or a check=True argument checks the return code of the command (if not zero, an exception is thrown).

To interact with the command (input / output) while it is still running before its completion, you can explicitly create a subprocess.Popen object .