Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using subprocess.run with arguments containing quotes

The command I'm trying to run looks like this:

xvfb-run --auto-servernum --server-args="-screen 0 640x480x24" --error-file=/dev/stdout /opt/myExecutable

This is what I have in Python3:

args = ['xvfb-run', '--auto-servernum','--server-args="-screen 0 640x480x24"', '--error-file=/dev/stdout', '/opt/myExecutable']
command = ' '.join(xvfbArgs)
print(f'Command: {command}')
subprocess.run(xvfbArgs)

I get the following:

Unrecognized option: "-screen
use: X [:<display>] [option]
...
segfault
...
Command: xvfb-run --auto-servernum --server-args="-screen 0 640x480x24" --error-file=/dev/stdout /opt/myExecutable

The printed command is correct.

I also tried with "-server-args='-screen 0 640x480x24'" (inverted " and ' which led to the same result (Unrecognized option: '-screen)

What goes on in subprocess.run that changes --server-args="-screen 0 640x480x24"?

like image 387
Nepoxx Avatar asked Jul 17 '26 12:07

Nepoxx


1 Answers

Here's a simple way to tell what the command you pass to subprocess.run should look like. In the shell (not Python, a regular shell), insert python -c 'import sys; print(sys.argv[1:])' before the command you want to run:

19:59 ~ $ python -c 'import sys; print(sys.argv[1:])' xvfb-run --auto-servernum --server-args="-screen 0 640x480x24" --error-file=/dev/stdout /opt/myExecutable
['xvfb-run', '--auto-servernum', '--server-args=-screen 0 640x480x24', '--error-file=/dev/stdout', '/opt/myExecutable']

The resulting list is exactly what you should pass to subprocess.run. Here, we can see that the shell converted the --server-args="-screen 0 640x480x24" in the input into a single argument with no quotes in it.

like image 118
user2357112 supports Monica Avatar answered Jul 20 '26 00:07

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!