如何在Python中打印文字/带引号的字符串以确保安全?

huangapple go评论63阅读模式
英文:

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:

&#39;hello world&#39;

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&#39;&#39;&#39;echo -n {quote(s)} | python -c &#39;from glob import glob; import sys; print(glob(sys.stdin.read()))&#39;&#39;&#39;

Keep your Python code static and supply arguments to it, in this case via stdin.

huangapple
  • 本文由 发表于 2023年1月9日 15:10:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定