Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

python - 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"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Correct syntax would be:

args = [
    'xvfb-run',
    '--auto-servernum',
    '--server-args=-screen 0 640x480x24',
    '--error-file=/dev/stdout',
    '/opt/myExecutable'
]

try:
    from pipes import quote  # Python 2
except ImportError:
    from shlex import quote  # Python 3

command_str = ' '.join(quote(s) for s in args)
print(f'Command: {command_str}')

subprocess.run(args) # or subprocess.run(command_str, shell=True)

Note that there are no literal quotes here at all -- the only quotes are Python syntax. In bash, unescaped quotes are syntax, not data, even when they exist part of the way through a string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...