【问题标题】:Writing all lines of finger command编写手指命令的所有行
【发布时间】:2020-06-07 20:18:27
【问题描述】:

我是 Python/树莓派的新手。我正在尝试将finger 命令的所有行写入我的网络服务器。我的代码是这样编写的,它只返回第二行。

请参阅下面的代码:

import sys
import os
import time
import datetime
import pytz
import subprocess


then=datetime.datetime.now(pytz.utc)  
TempString=str(then.astimezone(pytz.timezone('US/Eastern')))
TempString=TempString+"</br>" 

print("The following is the result of the Terminal 
Command 
$finger…")
p=subprocess.Popen("finger", shell=True, 
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
 print(line)
 TempStringF=line
retval=p.wait()


print("The following is the string stored in 
TempStringF")
print(TempStringF)
print("Opening WWW Index File for Writing…")

file=open('/var/www/html/index.html','w')
file.write(TempString)
file.write(str(TempStringF))
file.close()

print("Index file has been updated and closed…") 

【问题讨论】:

    标签: python apache raspberry-pi


    【解决方案1】:

    您的for 循环是问题所在:

    for line in p.stdout.readlines():
        print(line)
        TempStringF=line
    

    每次循环运行时,TempStringF 将被 line 的新内容覆盖。相反,将您的累积变量声明为循环外的空字符串,然后在循环中附加到它:

    temp_string_f = ""      # recommended style in Python is snake_case, not CapsCase
    for line in p.stdout.readlines():
        print(line)
        temp_string_f += line + "<br>"
    

    【讨论】:

    • 以下是终端命令 $finger... b'Login Name Tty Idle Login Time Office Office Phone\n' Traceback (最近一次通话最后一次): File "/home/pi /Documents/LAB4part2.py",第 18 行,在 TempStringF =line+"" TypeError: can't concat str to bytes
    • 我添加了.encode来清除错误,但我仍然只打印一行
    • 2020-06-08 23:45:44.025504-04:00 pi *tty1 6d Jun 6 14:18
    • 我刚刚编辑了我的答案,因为我犯了一个愚蠢的错误。最后一行应该是temp_string_f += line + "&lt;br&gt;",使用+= 而不是=现在它应该可以按预期工作了...
    猜你喜欢
    • 2018-04-24
    • 2015-11-11
    • 2023-03-31
    • 2010-10-10
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多