我要运行的命令如下:
xvfb-run --auto-servernum --server-args="-screen 0 640x480x24" --error-file=/dev/stdout /opt/myExecutable
这就是我在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)
我得到以下信息:
Unrecognized option: "-screen
use: X [:<display>] [option]
...
segfault
...
Command: xvfb-run --auto-servernum --server-args="-screen 0 640x480x24" --error-file=/dev/stdout /opt/myExecutable
打印的命令正确。
我还尝试了"-server-args='-screen 0 640x480x24'"
(倒置"
和'
导致相同的结果(Unrecognized option: '-screen
)
subprocess.run
中发生的变化改变了--server-args="-screen 0 640x480x24"
?
答案 0 :(得分:3)
正确的语法为:
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)
请注意,这里根本没有 文字引号-唯一的引号是Python语法。在bash中,未转义的引号是语法,而不是数据,即使它们存在于字符串中也是如此。
答案 1 :(得分:1)
请不要将命令合并为字符串,然后也不要在引号中放置引号以保护字符串不受shell攻击。
args = ['xvfb-run', '--auto-servernum','--server-args=-screen 0 640x480x24', '--error-file=/dev/stdout', '/opt/myExecutable']
print(f'Command: {args}')
subprocess.run(args)