Python curses 不适用于命令替换
Python curses does not work with command substitution
我正在使用 python 项目 pick 到 select 列表中的一个选项。下面的代码 returns 选项和索引。
option, index = pick(options, title)
Pick 使用 python 中的 curses 库。我想将 python 脚本的输出传递给 shell 脚本。
variable output = $(pythonfile.py)
但它卡在了诅咒屏幕上。它不能画任何东西。这可能是什么原因?
要将 Python 脚本的输出传递给 Bash 变量,您需要在变量声明中指定用于打开 python 文件的命令。
像这样:
variable_output=$(python pythonfile.py)
此外,如果你想将变量从Python传递到bash,你可以使用Python的sys模块然后重定向标准错误。
像这样:
test.py
import sys
test_var = (str(3 + 3))
sys.exit(test_var)
test.sh
test_var=$(python3 test.py 2>&1)
echo $testvar
现在,如果我们 运行 test.sh
我们得到输出 6
。
pick
会卡住,因为当您使用 $(pythonfile.py)
时,shell 会像管道一样重定向 pythonfile.py
的输出。此外,pick
的输出包含用于更新屏幕的字符(不是您想要的)。您可以通过
解决这些问题
- 将
pythonfile.py
的输出重定向到 /dev/tty
- 确保您的
pythonfile.py
将其结果写入标准错误,并且
- 将 shell 脚本中的标准错误定向到
$(...)
构造的输出。
例如:
#!/bin/bash
foo=$(python basic.py 2>&1 >/dev/tty )
echo "result '$foo'"
并在pythonfile.py
中做
import sys
print(option, index, file=sys.stderr)
而不是
print(option, index)
我正在使用 python 项目 pick 到 select 列表中的一个选项。下面的代码 returns 选项和索引。
option, index = pick(options, title)
Pick 使用 python 中的 curses 库。我想将 python 脚本的输出传递给 shell 脚本。
variable output = $(pythonfile.py)
但它卡在了诅咒屏幕上。它不能画任何东西。这可能是什么原因?
要将 Python 脚本的输出传递给 Bash 变量,您需要在变量声明中指定用于打开 python 文件的命令。
像这样:
variable_output=$(python pythonfile.py)
此外,如果你想将变量从Python传递到bash,你可以使用Python的sys模块然后重定向标准错误。
像这样:
test.py
import sys
test_var = (str(3 + 3))
sys.exit(test_var)
test.sh
test_var=$(python3 test.py 2>&1)
echo $testvar
现在,如果我们 运行 test.sh
我们得到输出 6
。
pick
会卡住,因为当您使用 $(pythonfile.py)
时,shell 会像管道一样重定向 pythonfile.py
的输出。此外,pick
的输出包含用于更新屏幕的字符(不是您想要的)。您可以通过
- 将
pythonfile.py
的输出重定向到/dev/tty
- 确保您的
pythonfile.py
将其结果写入标准错误,并且 - 将 shell 脚本中的标准错误定向到
$(...)
构造的输出。
例如:
#!/bin/bash
foo=$(python basic.py 2>&1 >/dev/tty )
echo "result '$foo'"
并在pythonfile.py
中做
import sys
print(option, index, file=sys.stderr)
而不是
print(option, index)