Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to run the bash eval command in python?

Tags:

python

bash

Attempting to convert an old bash script to python. The trouble is that I do not know very much about bash. Is there an equivalent python command for the bash command eval? Eval is used in the bash program like this:

eval "(/usr/path/exec/file) &"

where "file" is an executable file.

If there is no equivalent can someone provide a decent explanation as to what eval is doing here? I'm sorry if this is rudimentary but this is the first bash script I've ever looked at and I am very confused

like image 303
Thomas Britton Avatar asked Apr 02 '26 02:04

Thomas Britton


1 Answers

There are a couple of things going on there. First you are running inside a bash subshell, that is the parenthesis part. But probably that's not all that important since no variables are changed inside that subshell.

Next you are running a program and file descriptors are however copied so stdin, stdout, and stderr are the same.

And you are running that in the background.

So let's break these down into Python. As mentioned before, we can ignore the subshell part.

As for running the program, os.system() or subprocess.call is the equivalent of running a command without having to capture or change input or output.

More often you do need to capture output so the equivalent of

 x=$(/path/to/exec/file)

is in Python is

 x = subprocess.check_output('/path/to/exec/file')

See Replacing /bin/sh backquote for more info.

Finally, there is part about running in the background. For that the most equivalent match is subprocess.popen as mentioned in one of the other answers. There is also os.fork() but that doesn't work on all OS's, especially Windows. You might also want to consider using threads.

like image 146
rocky Avatar answered Apr 04 '26 16:04

rocky