gpt4 book ai didi

python - 从 bash 运行 python 时输入丢失字符串格式

转载 作者:行者123 更新时间:2023-12-04 19:19:39 24 4
gpt4 key购买 nike

我通过 ssh 登录并运行 bash。在这些 bash 命令中,我需要调用 python 文件中的特定函数并将字符串参数传递给该函数。

我现在拥有的:

echo "commands" | ssh into instance

其中命令包含
python -c 'from python file import myfunction;
myfunction({}) ' ... .format(myvariable)

myvariable 是一个包含多个单词的字符串。

但是,当 ssh 完成并执行命令时,调试日志显示 myvariable 周围的引号消失了,当传递给 myfunction 时,我收到未定义输入变量的错误。

如何确保 myvariable 保持字符串?

最佳答案

这通常是由于认为引号是上下文感知的。他们不是。

例子:

var="select * from table where name="value" order by name"

作为一个人类你可能会认为既然这是一条 SQL 语句,显然 bash 会知道中间的引号是嵌套的,并且会像这样读取字符串:
var="select * from table where name="value" order by name"
|-----| Nested
|----------------------------------------------------| Everything

然而,Bash 并不那么聪明。它读取这样的字符串:
var="select * from table where name="value" order by name"
|-------------------------------| |--------------|
Quoted string #1 Quoted #2

文字值被连接起来,中间引号“消失”的净效果。该语句等效于:
var="select * from table where name=value order by name"

相反,您必须告诉 bash 引号是带有转义的文字数据:
var="select * from table where name=\"value\" order by name"

Shellcheck自动对此发出警告。

关于python - 从 bash 运行 python 时输入丢失字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24539108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com