英文:
How to print literal/quoted string in python for safety purpose?
问题
以下是要翻译的代码部分:
s = "hello world"
print(quote(s))
在运行它时,你将获得:
"hello world"
这里是我真实用例:我想通过Fabric在远程机器上运行glob
,而glob
的搜索模式由用户提供。因此,我需要确保字符串被正确引用。以下是示例代码(我已经知道repr
是正确的方法):
import shlex
glob_pattern = 'some-data/*' # 用户输入,可能格式错误
script = 'from glob import glob; print(glob({}))'.format(repr(glob_pattern))
cmd = 'python -c {}'.format(shlex.quote(script))
connection.run(cmd) # 使用Fabric连接在远程节点上运行脚本
英文:
Given the following python script:
s = "hello world"
print(s)
When you run it you will get
hello world
If I want the output to be
"hello world"
Is there any build-in quote/escape method can do this? For example
s = "hello world"
print(quote(s))
Here is my real world use case: I want to run glob
on a remote machine via fabric. And the search pattern of glob
is provided by user. So I need to ensure the string are quoted properly. Here is the sample code (I already know repr
is the right method)
import shlex
glob_pattern = 'some-data/*' # user input, maybe malform
script = 'from glob import glob; print(glob({}))'.format(repr(glob_pattern))
cmd = 'python -c {}'.format(shlex.quote(script))
connection.run(cmd) # use a fabric connection to run script on remote node
答案1
得分: 2
是的,这里有 --> print(repr(s))
输出:
'hello world'
你可以在这里了解更多关于 repr()
的信息 --> <https://www.geeksforgeeks.org/python-repr-function/>。
英文:
Yes, there is --> print(repr(s))
Output:
'hello world'
You can read more about repr()
for example here --> <https://www.geeksforgeeks.org/python-repr-function/>
答案2
得分: 2
你可以使用 repr
来生成你的字符串的有效文字表示。然而,与其在有效的 bash 文字表示内生成有效的 Python 字符串文字,你可能应该考虑像这样做:
from shlex import quote
command = f'''echo -n {quote(s)} | python -c 'from glob import glob; import sys; print(glob(sys.stdin.read()))''''
保持你的 Python 代码静态,并通过 stdin 在这种情况下提供参数给它。
英文:
You can use repr
to produce a valid literal of your string. However, instead of producing a valid Python string literal inside a valid bash literal, you should probably pursue something like this instead:
from shlex import quote
command = f'''echo -n {quote(s)} | python -c 'from glob import glob; import sys; print(glob(sys.stdin.read()))'''
Keep your Python code static and supply arguments to it, in this case via stdin.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论