How to remove comma from end of line in Python?

How to remove a comma from the end of a line? I tried

awk = subprocess.Popen([r"awk", "{print $10}"], stdin=subprocess.PIPE)
awk_stdin = awk.communicate(uptime_stdout)[0]
print awk_stdin
temp = awk_stdin
t = temp.strip(",")

also tried t = temp.rstrip(","), both do not work.


This is the code:

uptime = subprocess.Popen([r"uptime"], stdout=subprocess.PIPE)
uptime_stdout = uptime.communicate()[0]
print uptime_stdout

awk = subprocess.Popen([r"awk", "{print $11}"], stdin=subprocess.PIPE)
awk_stdin = awk.communicate(uptime_stdout)[0]
print repr(awk_stdin)
temp = awk_stdin
tem = temp.rstrip("\n")
logfile = open('/usr/src/python/uptime.log', 'a')
logfile.write(tem + "\n")
logfile.close()

This is the conclusion:

 17:07:32 up 27 days, 37 min,  2 users,  load average: 5.23, 5.09, 4.79

5.23,
None
Traceback (most recent call last):
  File "uptime.py", line 21, in ?
    tem = temp.rstrip("\n")
AttributeError: 'NoneType' object has no attribute 'rstrip'
+3
source share
5 answers

When you speak

awk = subprocess.Popen([r"awk", "{print $11}"], stdin=subprocess.PIPE)
awk_stdout = awk.communicate(uptime_stdout)[0]

then the output of the awk process is output to standard output (for example, to the terminal). awk_stdoutset to None. awk_stdout.rstrip('\n')calls AttributeErrorbecause it Nonedoes not have an attribute rstrip.

When you speak

awk = subprocess.Popen([r"awk", "{print $11}"], stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE)
awk_stdout = awk.communicate(uptime_stdout)[0]

then nothing is printed in stdout (for example, a terminal), but awk_stdoutreceives the command output awkas a string.

+7
source

Err, how about the venerable:

if len(str) > 0:
    if str[-1:] == ",":
        str = str[:-1]

, rstrip , - , awk, , . .


, . :

str = "hello,"
print str.rstrip(",")

str = "hello,\n"
print str.rstrip(",")
print str.rstrip(",\n")

:

hello
hello,

hello

, , rstrip ",\n".


, , :

uptime = subprocess.Popen([r"uptime"], stdout=subprocess.PIPE)
uptime_stdout = uptime.communicate()[0]
print uptime_stdout
awk = subprocess.Popen([r"awk", "{print $11}"], stdin=subprocess.PIPE)
awk_stdin = awk.communicate(uptime_stdout)[0]
print repr(awk_stdin)
temp = awk_stdin
tem = temp.rstrip("\n")
logfile = open('/usr/src/python/uptime.log', 'a')
logfile.write(tem + "\n")
logfile.close()

print , ?

uptime $11:

23:43:10 up  5:10,  0 users,  load average: 0.00, 0.00, 0.00

.

, script.

+7

:

str = '1234,,,'
str = str.rstrip(',')
+2

, , awk_stdin (print repr(awk_stdin), ), , ( RE, , ! -).

+1

/, - :

a_string = 'abcdef,\n'
a_string.strip().rstrip(',') if a_string.strip().endswith(',') else a_string.strip()

.

, , , :

a_string.strip().rstrip(',')
0

Source: https://habr.com/ru/post/1744181/


All Articles