【问题标题】:Output of python script that run after raspberry pi boot树莓派启动后运行的python脚本的输出
【发布时间】:2017-08-22 09:25:12
【问题描述】:

我的 python 脚本的输出存在问题,该脚本在树莓派启动后自动运行并将其输出写入我使用 crontab 创建的 output.txt 文件中。我的代码是这样的:

while True:
f=open('test.txt','w+')
d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y/%m/%d %H:%M:%S")
print(reg_format_date)
f.write(reg_format_date)        
for x in range (27,14,-1):
    key_in=GPIO.input(x)
    if key_in==0:
         y='1'
         print(y)
        f.write(y)              

    else:
        y='0'
        print(y)
        f.write(y)
    f.close()

在 crontab 我有这样写

@reboot python /home/pi/test.py >> /home/pi/output.txt&

我的脚本的输出是:

2017/08/13 01:49:12 
0
1
1
1
1
0
0
0
0
0
0
0
0

我想要的输出格式:2017/08/12 01:33:28 0111100000000

【问题讨论】:

    标签: python cron raspberry-pi output autorun


    【解决方案1】:

    来自帮助(打印):

    关于内置模块内置函数打印的帮助:

    print(...)
        print(value, ..., sep=' ', end='\n', file=sys.stdout)
    
        Prints the values to a stream, or to sys.stdout by default.
        Optional keyword arguments:
        file: a file-like object (stream); defaults to the current sys.stdout.
        sep:  string inserted between values, default a space.
        end:  string appended after the last value, default a newline.
    

    因此,为了在同一行上打印,您的代码将被修改,以便您在第一次打印后放置一个逗号,这样它就不会进入新行并且看起来像:

    while True:
    f=open('test.txt','w+')
    d_date = datetime.datetime.now()
    reg_format_date = d_date.strftime("%Y/%m/%d %H:%M:%S")
    print(reg_format_date),
    f.write(reg_format_date)        
    for x in range (27,14,-1):
        key_in=GPIO.input(x)
        if key_in==0:
             y='1'
             print(y,end='')
            f.write(y)              
    
        else:
            y='0'
            print(y,end='')
            f.write(y)
        f.close()
    

    【讨论】:

    • 打印功能没问题,但是当它写入文件时,它会转到新行。那么如何在文件的同一行中写入
    • 当我通过 F5 手动运行代码时,它的输出将是 2017/08/22 11:46:08 1111111111111 但如果它是使用 crontab 自动运行的,当它写入文件时它会转到换行符
    • 我试过stackoverflow.com/questions/17290829/…,但结果还是一样。我不知道如何获得预期的输出
    猜你喜欢
    • 2015-05-11
    • 2023-01-08
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多