使用 Python 输出调用程序
Call Programs with Python Output
我想用 python 生成的参数调用 c 程序 display_output
,但是我不确定如何制定语法。我试过了
./display_output (python -c "print 'A' * 20")
但我得到
bash: syntax error near unexpected token `python'
我想这符合我最初的问题,可以帮助我解决这个问题。我能找到的尝试 运行 python cmd 行输出作为 bash 命令的唯一方法是将 | bash
附加到命令。但是,有更好的方法吗?
(python -c "print 'ls'") | bash
我显然不知道自己的方法 Bash,但我确信有更合适的方法来做到这一点。
当bash 在命令可以出现的地方看到一个左括号时,它将启动一个子shell 到运行 包含的命令。您当前拥有它们的地方不是命令可以到达的地方。你想要的是 command substitution
./display_output $(python -c "print 'A' * 20")
# ...............^
如果生成的任何参数包含空格,您就会遇到麻烦(显然这个玩具示例不是这种情况。
要在 bash 中生成 20 "A" 的字符串,您可以这样写:
a20=$(printf "%20s" "") # generate a string of 20 spaces
# or, the less readable but more efficient: printf -v a20 "%20s" ""
a20=${a20// /A} # replace all spaces with A's
中的模式替换
我想用 python 生成的参数调用 c 程序 display_output
,但是我不确定如何制定语法。我试过了
./display_output (python -c "print 'A' * 20")
但我得到
bash: syntax error near unexpected token `python'
我想这符合我最初的问题,可以帮助我解决这个问题。我能找到的尝试 运行 python cmd 行输出作为 bash 命令的唯一方法是将 | bash
附加到命令。但是,有更好的方法吗?
(python -c "print 'ls'") | bash
我显然不知道自己的方法 Bash,但我确信有更合适的方法来做到这一点。
当bash 在命令可以出现的地方看到一个左括号时,它将启动一个子shell 到运行 包含的命令。您当前拥有它们的地方不是命令可以到达的地方。你想要的是 command substitution
./display_output $(python -c "print 'A' * 20")
# ...............^
如果生成的任何参数包含空格,您就会遇到麻烦(显然这个玩具示例不是这种情况。
要在 bash 中生成 20 "A" 的字符串,您可以这样写:
a20=$(printf "%20s" "") # generate a string of 20 spaces
# or, the less readable but more efficient: printf -v a20 "%20s" ""
a20=${a20// /A} # replace all spaces with A's
中的模式替换