I want to print specified output in subrocess
Here is my code:
from subprocess import check_output
output = check_output(['python3', 'code.py']).decode('ascii')
print(output)
The output is:
Tom
John
How can I print just Tom or just John instead of both of them?
I have tried print(output[0]) to print Tom but I get only T.
You have single string and you can use any string's function.
You can split it and create list with lines
lines = output.split('\n')
And then display only first line
print(lines[0])
Let's take a look on steps you've already done:
You call check_output() and it returns output in the form of bytes;
Then You call bytes.decode(), which returns str.
As a result you get multi-line string. You've tried to access to first line using index 0, but you got first char instead of first line. It happened, cause accessing to string by index will return you char from this index.
To get first line you should split lines of your multi-line string (convert str to list of str). There's built-in function str.splitlines() which does what you need.
So, to upgrade your code we need to add one more line before your print() statement:
output_lines = output.splitlines()
After that you can access to line by index:
print(output_lines[0])
Related
I am reading text file using
source= open(curr_file,"r")
lines= source.readlines()
This converts every line in my text file to a list, but some items in my list are created with double quotes while some are created with single quotes like below.
['[INFO] Name: Xxxx, section: yyyy, time: 21.2, status: 0\n', "proof:proof1,table: db.table_name,columns:['column_1'],count:10,status:SUCCESS\n",'run time: 30 seconds\n']
The first item in list is created with single quotes, while the second is created with double quotes.
When trying to convert the above to dictionary
new_line= dict(x.split(":"),1) for x in line.split(","))
It gives me a value error
Value error: dictionary update sequence element has length 1; 2 is required
The above error is because it considers the entire string under double quotes as single value and it's not able to convert it to dictionary.
Is there a way to convert it to single quotes instead of double. I tried using replace, strip. But nothing helps.
Expected output:
{
Name:Xxxx,
section:yyyy,
time:21.2,
proof:proof1
table:db.table_name
status: success
}
The quotes has nothing to do with the error. The exterior quotes of each line are not part of the str object. They are only printed to you know it is a str. The single quotes are switched to double because the content has single quotes in it, then single quotes cannot be used to delimit the str. But again, that is only a change in what is printed not in what is stored in memory.
Try to do it in steps and print the intermediate objects you get to debug the program.
for x in line: #prints nicer than print(line)
print(x)
arg = [x.split(":",1) for x in line.split(",")]
for x in arg:
print(x)
new_line = dict(arg)
you should get printed tuples with two elements
for convert your one line(str) to dict, you can use dictionary comprehension:
new_line = dict(x.split(":",1) for x in line.split()
#!/usr/bin/env python
import os,subprocess,re
f=open("/var/tmp/disks_out","w")
proc=subprocess.Popen(['df', '-h'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=False)
out,err=proc.communicate()
for line in out:
f.write(line)
f.close()
f1=open("/var/tmp/disks_out","r")
disks=[]
for line in f1:
m=re.search(r'(c.*s0)',line)
if m:
disk=m.group(1)
disks.append(disk)
disks = disks[0][:-1]
slices =[disks+i for i in str(range(5))]
print(slices)
and the out put i am getting below:
['c0t5000CCA025A29894d0s0', 'c0t5000CCA025A29894d0s1', 'c0t5000CCA025A29894d0s3', 'c0t5000CCA025A29894d0s4', 'c0t50 00CCA025A29894d0s5', 'c0t5000CCA025A29894d0s6']
But i want to get output similar too:
c0t5000CCA025A29894d0s1,c0t5000CCA025A29894d0s2,c0t5000CCA025A29894d0s3
If you want to get it with commas:
print(','.join(slices))
or rather for python 2.7:
print ','.join(slices)
What you printed out was list, so python interpreted it as one. join() method joins every element of the iterable by passed string, more info here (for Python 2.7 as you put in tag) but it seems you are using Python 3 here.
I'm using Python 3 and I need to parse a line like this
-1 0 1 0 , -1 0 0 1
I want to split this into two lists using Fraction so that I can also parse entries like
1/2 17/12 , 1 0 1 1
My program uses a structure like this
from sys import stdin
...
functions'n'stuff
...
for line in stdin:
and I'm trying to do
for line in stdin:
X = [str(elem) for elem in line.split(" , ")]
num = [Fraction(elem) for elem in X[0].split()]
den = [Fraction(elem) for elem in X[1].split()]
but all I get is a list index out of range error: den = [Fraction(elem) for elem in X[1].split()]
IndexError: list index out of range
I don't get it. I get a string from line. I split that string into two strings at " , " and should get one list X containing two strings. These I split at the whitespace into two separate lists while converting each element into Fraction. What am I missing?
I also tried adding X[-1] = X[-1].strip() to get rid of \n that I get from ending the line.
The problem is that your file has a line without a " , " in it, so the split doesn't return 2 elements.
I'd use split(',') instead, and then use strip to remove the leading and trailing blanks. Note that str(...) is redundant, split already returns strings.
X = [elem.strip() for elem in line.split(",")]
You might also have a blank line at the end of the file, which would still only produce one result for split, so you should have a way to handle that case.
With valid input, your code actually works.
You probably get an invalid line, with too much space or even an empty line or so. So first thing inside the loop, print line. Then you know what's going on, you can see right above the error message what the problematic line was.
Or maybe you're not using stdin right. Write the input lines in a file, make sure you only have valid lines (especially no empty lines). Then feed it into your script:
python myscript.py < test.txt
How about this one:
pairs = [line.split(",") for line in stdin]
num = [fraction(elem[0]) for elem in pairs if len(elem) == 2]
den = [fraction(elem[1]) for elem in pairs if len(elem) == 2]
I have two text files which I'm trying to work with in python 2.7.7, structured as in these examples:
sequence_file.txt:
MKRPGGAGGGGGSPSLVTMANSSDDGYGGVGMEAEGDVEEEMMACGGGGE
positions.txt
10
7
4
What I want to do is insert a # symbol into the sequence at every position indicated in positions.txt:
MKR#PGG#AGGG#GGSPSLVTMANSSDDGYGGVGMEAEGDVEEEMMACGGGGE
At the moment, my code is as follows:
# Open sequence file, remove newlines:
with open ("sequence_file.txt", "r") as seqfile:
seqstring=seqfile.read().replace('\n', '').replace('\r', '')
# Turn sequence into list
seqlist = list(sequence)
# Open positions.txt, and use each line as a parameter for the insert() function.
with open("positions.txt") as positions:
for line in positions:
insertpoint = line.rstrip('\n')
seqlist.insert(insertpoint, '#')
seqlist = list(sequence)
The last block of that code is where it falls down. I'm trying to have it read the first line, trim the newline character (\n) and then use that line as a variable (insertpoint) in the insert() command. However, whenever I try this it tells me:
Traceback (most recent call last):
File "<pyshell#8>", line 4, in <module>
seqlist.insert(insertpoint, '#')
TypeError: an integer is required
If I test it out and try 'print insertpoint' it produces the number correctly, and so my interpretation of the error is that when I use the insert() command it is reading 'insertpoint' as text rather than the variable that was just set.
Can anyone suggest what might be going wrong with this?
What happens is that str.rstrip() returns a string, but insert() expects an integer.
Solution: Convert that string into an integer:
insertpoint = int(line.rstrip('\n'))
Note: When you print insertpoint it is shown without the '' but it is a string. You can check this by printing its type:
print(type(insertpoint)) # <type 'str'>
It appears you might need to put int() around insertpoint:
seqlist.insert(int(insertpoint), '#')
so this piece of code is meant to take a line from a file and replace the certain line from the string with a new word/number, but it doesn't seem to work :(
else:
with open('newfile', 'r+')as myfile:
x=input("what would you like to change: \nname \ncolour \nnumber \nenter option:")
if x == "name":
print("your current name is:")
test_lines = myfile.readlines()
print(test_lines[0])
y=input("change name to:")
content = (y)
myfile.write(str.replace((test_lines[0]), str(content)))
I get the error message TypeError: replace() takes at least 2 arguments (1 given), i don't know why (content) is not accepted as an argument. This also happens for the code below
if x == "number":
print ("your current fav. number is:")
test_lines = myfile.readlines()
print(test_lines[2])
number=(int(input("times fav number by a number to get your new number \ne.g 5*2 = 10 \nnew number:")))
result = (int(test_lines[2])*(number))
print (result)
myfile.write(str.replace((test_lines[2]), str(result)))
f=open('newfile', 'r')
print("now we will print the file:")
for line in f:
print (line)
f.close
replace is a function of a 'str' object.
Sounds like you want to do something like (this is a guess not knowing your inputs)
test_lines[0].replace(test_lines[0],str(content))
I'm not sure what you're attempting to accomplish with the logic in there. looks like you want to remove that line completely and replace it?
also i'm unsure what you are trying to do with
content = (y)
the output of input is a str (which is what you want)
EDIT:
In your specific case (replacing a whole line) i would suggest just reassigning that item in the list. e.g.
test_lines[0] = content
To overwrite the file you will have to truncate it to avoid any race conditions. So once you have made your changes in memory, you should seek to the beginning, and rewrite everything.
# Your logic for replacing the line or desired changes
myfile.seek(0)
for l in test_lines:
myfile.write("%s\n" % l)
myfile.truncate()
Try this:
test_lines = myfile.readlines()
print(test_lines[0])
y = input("change name to:")
content = str(y)
myfile.write(test_lines[0].replace(test_lines[0], content))
You have no object known purely as str. The method replace() must be called on a string object. You can call it on test_lines[0] which refers to a string object.
However, you may need to change your actual program flow. However, this should circumvent the error.
You need to call it as test_lines[0].replace(test_lines[0],str(content))
Calling help(str.replace) at the interpreter.
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
Couldn't find the docs.