gpt4 book ai didi

python - 将 bash 输出传递给 python 脚本时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:49 24 4
gpt4 key购买 nike

我是编程新手,我在互联网上搜索了一种将 bash 输出传递给 Python 脚本的方法。

我在 bash 中想出了这个。

XAS_SVN=`svn info` 
ssh hudson@test "python/runtests.py $XAS_SVN"

这是在 python 中。

import sys
print sys.argv[1]

当我 echo $SVN_INFO 时,我得到了结果。

Path: . URL: //svn/rnd-projects/testing/python Repository Root: //svn/rnd-projects Repository UUID: d07d5450-0a36-4e07-90d2-9411ff75afe9 Revision: 140 Node Kind: directory Schedule: normal Last Changed Author: Roy van der Valk Last Changed Rev: 140 Last Changed Date: 2009-06-09 14:13:29 +0200 (Tue, 09 Jun 2009)

但是 python 脚本只打印以下内容。

Path:

这是为什么,我该如何解决? $SVN_INFO 变量不是字符串类型?

我知道 subprocess 模块和 Popen 函数,但我认为这不是解决方案,因为 python 脚本在另一台服务器上运行。

最佳答案

由于变量中有空格,因此需要转义它们或读取脚本中的所有参数:

print ' '.join(sys.argv[1:])

但使用 stdin/stdout 进行通信可能会更好,尤其是当输出中可能有一些字符容易被 shell 解释时(如“`$”)。在 python 脚本中执行:

for l in sys.stdin:
sys.stdout.write(l)

在外壳中:

svn info | ssh hudson@test python/runtests.py

关于python - 将 bash 输出传递给 python 脚本时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1333107/

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