简体   繁体   English

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

[英]Problem passing bash output to a python script

I'm fairly new to programming and I searched the internet for a way to pass bash output to a Python script. 我对编程还很陌生,因此我在互联网上搜索了一种将bash输出传递给Python脚本的方法。

I came up with this in bash. 我想到了这个。

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

And this in python. 而这在python中。

import sys
print sys.argv[1]

When I echo $SVN_INFO I get the result. 当我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) 网址:// svn / rnd-projects / testing / python信息库根目录:// svn / rnd-projects信息库UUID:d07d5450-0a36-4e07-90d2-9411ff75afe9修订:140节点种类:目录日程:正常最近更改作者:Roy van der Valk上次更改时间:140上次更改日期:2009-06-09 14:13:29 +0200(星期二,2009年6月9日)

However the python script just prints the following. 但是,python脚本仅显示以下内容。

Path: 路径:

Why is this and how can I solve this? 为什么会这样,我该如何解决呢? I the $SVN_INFO variable not of string type? 我的$ SVN_INFO变量不是字符串类型吗?

I know about the subprocess module and the Popen function, but I don't think this is a solution since the python script runs on another server. 我知道子进程模块和Popen函数,但是我认为这不是解决方案,因为python脚本在另一台服务器上运行。

Since you have spaces in the variable, you need to escape them or read all the arguments in your script: 由于变量中有空格,因此需要对其进行转义或读取脚本中的所有参数:

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

But it might be better to use stdin/stdout to communicate, especially if there can be some characters susceptible to be interpreted by the shell in the output (like "`$'). In the python script do: 但是最好使用stdin / stdout进行通信,尤其是在输出中的某些shell易于理解的字符的情况下(例如“ $”),在python脚本中执行以下操作:

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

and in shell: 并在外壳中:

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

Yes, you need to put in quotes your input to python/runtest.py because otherwise argv[1] gets it only up to the first space. 是的,您需要在python / runtest.py中用引号引起来,因为否则argv [1]仅将其保留到第一个空格。 Like this: 像这样:

ssh hudson@test "python/runtest.py \"$XAS_SVN\""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM