Python如何对变量进行shellscape?

2024-06-09 12:11:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从python运行以下shell脚本:

AliasScript = "osascript -e 'tell application \"Finder\" to make alias at \
POSIX file \"" + dirAlbumName + "\" as alias to \
POSIX file \"" + dirName + "\" as alias'"

os.system(AliasScript + "&> /dev/null")

只有当dirAlbumName和/或dirName变量不包含任何元字符(或者称为特殊字符)时,它才起作用,例如\'"。例如,如果dirName=/\/\/\ !@#$%^&*()|?"'"" /\?\/,我会得到一个语法错误。你知道吗

如何对这些变量进行shell转义?我试着根据从here读到的内容使用shlex,但是我无法让它工作。例如,我试过shlex.quote(dirName),但没有成功。你知道吗

编辑:

要清楚的是,这段代码将在一个循环中运行数百次,其中dirNamedirAlbumName的值不同,因此我不能手动转义它们。你知道吗


Tags: to脚本finderapplicationasaliasshellposix
3条回答

您可以使用python字符串格式准确地传递所需内容,例如,您需要执行以下操作:

dirAlbumName=r"jim&bo"
dirName=r"jon smith"
AliasScriptTemplate = r"osascript -e 'tell application \"{0}\" to make alias at \
POSIX file \"{1}\" as alias to \
POSIX file \"{2}\" as alias'"
AliasScript = AliasScriptTemplate.format("Finder",dirAlbumName,dirName)
AliasScript += r'&> /dev/null'
os.system(AliasScript)

这里的关键是,在字符串前面加上r前缀意味着python不会对字符串“做”任何事情,而是保持它的原样。更多详情请点击这里https://www.linode.com/docs/development/python/string-manipulation-python-3/

请注意,python的subprocess模块非常适合于运行脚本,并允许您更好地控制正在执行的操作,包括将stderr和stdout重定向到文件/变量/,请参见此处的解释https://www.programcreek.com/python/example/94463/subprocess.run

考虑使用shlex.quote模块对dirAlnumNamedirName进行转义。我不熟悉你使用的脚本语言,但这里发生了什么。你知道吗

>>> import shlex
>>> dirname="""/\/\/\ !@#$%^&*()|?"'"" /\?\/"""
>>> print(shlex.quote(dirname))
'/\/\/\ !@#$%^&*()|?"'"'"'"" /\?\/'
>>> print (dirname)
/\/\/\ !@#$%^&*()|?"'"" /\?\/
>>>

这是一个活生生的例子

>>> fname = "\name"
>>> import os
>>> os.system("touch " +fname)
touch: missing file operand
Try 'touch  help' for more information.
sh: 2: ame: not found
32512
>>> import shlex
>>> os.system("touch " +shlex.quote(fname))
0

一种更安全的方法是使用subprocess模块并完全避免shell

>>> import subprocess
>>> subprocess.Popen(['touch', '\name'])
>>> _.wait()
0

我复制了你的问题。我已经创建了一个名为“$$%@@”的文件夹。每当“#”出现时,需要传递转义字符。 例如:

/path/to/folder/$\#$%@@

相关问题 更多 >