Linux cat命令在python中无法正常工作

时间:2017-03-11 07:46:22

标签: python

我编写了一个脚本来从文件中获取一些信息。

 #!/usr/bin/python
 import pxssh
 import os
 import sys
 path = os.getcwd()
 conf = sys.argv[1]
 print type(path)
 print type(conf)
 print path
 print conf
 HOST_IP=os.system("cat %s/%s | grep 'HOST_IP'| cut -d '=' -f2")%(path,conf)

这是我得到的错误。

`[root@135 bin]# ./Jboss64.py ../conf/samanoj.conf
<type 'str'>
<type 'str'>
/root/Sanity/bin
../conf/samanoj.conf   --> This is the file present under conf folder
cat: %s/%s: No such file or directory
Traceback (most recent call last):
  File "./Jboss64_EA_EM_FM.py", line 11, in <module>
    LIVEQ_HOST_IP=os.system("cat %s/%s | grep 'LIVEQ_HOST_IP'| cut -d '=' -f2")%(path,conf)
TypeError: unsupported operand type(s) for %: 'int' and 'tuple'`

请帮我解决这个问题。

3 个答案:

答案 0 :(得分:4)

你应该这样写:

os.system("cat %s/%s | grep 'HOST_IP'| cut -d '=' -f2" % (path,conf))

在你的表达式中,首先执行os.system,仅在执行格式字符串运算符之后执行。 os.system return 0这就是你收到此错误的原因

如果使用格式化方法会更好:

os.system("cat {}/{} | grep 'HOST_IP'| cut -d '=' -f2".format(path, conf))

如果使用subprocess.Popen而不是os.system

,也会更好
Popen("cat {}/{} | grep 'HOST_IP'| cut -d '=' -f2".format(path, conf), shell=True)

答案 1 :(得分:0)

可能会有所帮助的事情:

  1. os.system已弃用,建议您使用subprocess.Popen 文档:https://docs.python.org/2/library/subprocess.html
  2. 你在哪里:

    LIVEQ_HOST_IP=os.system("cat %s/%s | grep 'LIVEQ_HOST_IP'| cut -d '=' -f2")%(path,conf)

  3. 在Python中构造字符串可能更容易,然后传递给bash。如下所示:

    output_str = "cat " +str(path) + "/" + str(conf) + " | grep 'LIVEQ_HOST_IP'| cut -d '=' -f2" 
    LIVEQ_HOST_IP=subprocess.Popen(output_str)
    

    subprocess(和os)接受一个用于调用系统函数的字符串,因此在传递给Popen之前,请确保该字符串是正确的。希望这会有所帮助。

答案 2 :(得分:0)

您可以尝试:

cmd = "cat {}/{} | grep 'HOST_IP'| cut -d '=' -f2".format(str(path), str(conf))
HOST_IP = subprocess.Popen(cmd)