简体   繁体   中英

Linux cat command is not working properly in python

I have written a script to get some information from a file.

 #!/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)

Here is the error I am getting .

`[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'`

Please help me to resolve this.

You should write like that:

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

In your expression, first is executed os.system, only after that executing format string operator. os.system return 0 that's why you got this error

Would be better if you use format method:

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

Also would be better if you use subprocess.Popen instead of os.system

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

Couple of things that may help:

  1. os.system is being deprecated, I suggest you use subprocess.Popen Docs here: https://docs.python.org/2/library/subprocess.html
  2. Where you have:

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

it may be easier to construct the string in Python, then pass to bash. So something like:

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

subprocess (and os ) take a string that is used to call system functions, so make sure that the string is correct before you pass to Popen . Hope this helps.

You can try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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