【问题标题】:How to use subprocess to write to file如何使用子进程写入文件
【发布时间】:2016-01-30 08:53:35
【问题描述】:

我正在尝试获取 adb logcat 并保存到文件中。我尝试了 POPEN 并调用如下

    f = open("/Users/log.txt")
    subprocess.call(["adb logcat"], stdout=f)
    f_read = f.read()
    print f_read

但我得到错误

  File "testPython.py", line 198, in getadbLogs
    subprocess.call(["adb logcat"], stdout=f)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
**OSError: [Errno 2] No such file or directory**

我不确定我做错了什么。是否可以使用子进程获取 adb logcat 日志?我检查了文件路径是否正确。

【问题讨论】:

    标签: android python python-2.7 subprocess logcat


    【解决方案1】:

    因为您在读取模式下打开了f (r)。如果不选择模式,默认模式为r模式。

    要写入文件,您应该使用w 模式,如下所示:

    f = open("/Users/log.txt", 'w')
    subprocess.call(["adb logcat"], stdout=f)
    f.close()
    
    f = open("/Users/log.txt")
    f_read = f.read()
    print f_read
    f.close()
    

    而使用with自动关闭文件会更简单:

    with open("/Users/log.txt", 'w') as f:
        subprocess.call(["adb logcat"], stdout=f)
    
    with open("/Users/log.txt") as f:
        f_read = f.read()
    
    print f_read
    

    【讨论】:

    • 是的,我也想通了。但是由于它是 adb logcat 它不断地转储到文件中。我应该如何阻止/杀死它?
    • @user2661518 你可以设置超时时间,例如:subprocess.call('python', timeout=2) 只会运行 python 2 秒。然后subprocess 将引发subprocess.TimeoutExpired 错误并说:Command 'python' timed out after 2 seconds
    • 因为我使用的是python2.7 subprocess.call 没有超时参数
    • @user2661518:好吧,看看herehere
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 2012-11-11
    • 1970-01-01
    相关资源
    最近更新 更多