def proc(self, config: dict, record_dir: str, danmu_path: str, current_state, state_change_time) -> None: p = Processor(config, record_dir, danmu_path) p.run() if config.get('spec', {}).get('uploader', {}).get('record', {}).get( 'upload_record', False) or config.get('spec', {}).get( 'uploader', {}).get('clips', {}).get( 'upload_clips', False): current_state.value = int(utils.state.UPLOADING_TO_BILIBILI) state_change_time.value = time.time() try: u = Uploader(p.outputs_dir, p.splits_dir, config) d = u.upload(p.global_start) except Exception as e: current_state.value = int(utils.state.ERROR) state_change_time.value = time.time() if d is None: current_state.value = int(utils.state.ERROR) state_change_time.value = time.time() else: if not config.get('spec', {}).get('uploader', {}).get( 'record', {}).get('keep_record_after_upload', True) and d.get( "record", None) is not None and not config.get('root', {}).get( 'uploader', {}).get('upload_by_edit', False): rc = BiliVideoChecker(d['record']['bvid'], p.splits_dir, config) rc.start() if not config.get('spec', {}).get('uploader', {}).get( 'clips', {}).get('keep_clips_after_upload', True) and d.get( "clips", None) is not None and not config.get('root', {}).get( 'uploader', {}).get('upload_by_edit', False): cc = BiliVideoChecker(d['clips']['bvid'], p.outputs_dir, config) cc.start() if config.get('root', {}).get('enable_baiduyun', False) and config.get( 'spec', {}).get('backup', False): current_state.value = int(utils.state.UPLOADING_TO_BAIDUYUN) state_change_time.value = time.time() try: from bypy import ByPy bp = ByPy() bp.upload(p.merged_file_path) except Exception as e: logging.error('Error when uploading to Baiduyun:' + str(e) + traceback.format_exc()) current_state.value = int(utils.state.ERROR) state_change_time.value = time.time() return if current_state.value != int(utils.state.LIVE_STARTED): current_state.value = int(utils.state.WAITING_FOR_LIVE_START) state_change_time.value = time.time()
def main(): tRange = [dt.datetime(2019, 10, 1), dt.datetime(2019, 10, 31)] product = 'cams_nrealtime' filename = '{product}_{date}.grib'.format(product=product, date=tRange[0].strftime('%Y%m')) filepath = os.path.join(CONFIG['ECMWF']['DATA_DIR'], filename) get_ECMWF_file(tRange, dataset=product, filepath=filepath) bp = ByPy() bp.upload(filepath, os.path.join(CONFIG['ECMWF']['BDY_DIR'], filename))
def uploadby(filedir,filename,flag): try: bp = ByPy() if flag: bp.mkdir(remotepath = filedir) # 上传某一文件到百度云网盘对应的远程文件夹 # ondup中参数代表复制文件,默认值为'overwrite',指定'newcopy'不会覆盖重复文件 if os.path.exists(filename): bp.upload(localpath= filename, remotepath= filedir, ondup='overwrite') os.remove(filename) except:logging.info('上传百度云失败')
def upLoad(t): bp = ByPy() for l in range(0, len(t) - 1): print(os.path.join(os.getcwd(), "tsdir", t[l])) try: bp.upload(localpath=os.path.join(os.getcwd(), "tsdir", t[l]), remotepath='bypy') print('上传完毕!') documentDelete(os.path.join(os.getcwd(), "tsdir", t[l])) except Exception as e: print(e)
def besync(path): # 云盘同步函数 可能因hash导致显示失败,但实际成功。 dir_name = '监控扩展数据' pan = ByPy() pan.mkdir(dir_name) for file in os.listdir(path): if os.path.isdir(file): # 判断 是文件夹跳过 continue else: filename = os.path.join(path, file) # 文件绝对路径 pan.upload(localpath=filename, remotepath=dir_name, ondup='newcopy') # 上传图片
def uploadby(filedir, filename, flag): try: bp = ByPy() if flag: bp.mkdir(remotepath=filedir) filename = os.path.join('./danmu', filename) if os.path.exists(filename): bp.upload(localpath=filename, remotepath=filedir, ondup='overwrite') os.remove(filename) except: print('fail')
def face_msg(msg): image_name = msg.file_name print(msg) print('接收图片') print(image_name) print(msg.receive_time) imagetime = str(msg.receive_time) msg.get_file('/root/weixin/' + msg.file_name) path = '/root/weixin/' + msg.file_name bp = ByPy() bp.upload(localpath=path, remotepath='dir_name', ondup='newcopy') print('上传成功' + path) print(msg)
def compress_and_upload(date): date_string = '%04d%02d%02d' % (date.year, date.month, date.day) folder_path = 'data/' + date_string folder_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), folder_path) if not os.path.exists(folder_path): LOG.error('%s does not exist', folder_path) return archive_path = folder_path + '.7z' if os.path.exists(archive_path): LOG.warning('%s already exists, it is removed first', archive_path) os.remove(archive_path) LOG.info('Compress and remove %s', folder_path) ret = subprocess.run(['7za', 'a', archive_path, folder_path]).returncode if ret != 0: LOG.error('Compressing %s returns nonzero code %d', folder_path, ret) return shutil.rmtree(folder_path, ignore_errors=True) LOG.info('Upload and remove %s', archive_path) bp = ByPy() ret = bp.upload(archive_path, 'dshare/data') if ret != 0 and ret != 60: LOG.error('Bypy upload returns nonzero code %d', ret) return os.remove(archive_path)
def record_start_stop(): global record_enable, record_flag, record_jud_flag, record_jud, record, start_time, tone_list, tone_flag, ten_sec_flag record_jud_flag = 0 record_flag = (-1) * record_flag if record_flag == -1: print("record start!") noti_rec_start.play(0) record = numpy.zeros(shape=[441000, 2], dtype=numpy.int16) ten_sec_flag = 1 # to extend reacord with 0 start_time = time.time() record_jud.cancel() elif record_flag == 1: noti_rec_stop.play(0) print("saving...") zero_num = 0 i = 1 while True: if (record[len(record) - i] == record[0]).any(): zero_num += 1 i += 1 else: break record = record[:len(record) - 1 - zero_num] now = time.time() now_time = time.strftime("%Y%m%d_%H%M%S") path = (now_time + ".wav") wavfile.write(path, 44100, record) print("local saved!") proc = subprocess.Popen(['ping', 'www.baidu.com'], stdout=subprocess.PIPE) time.sleep(2) proc.kill() result = proc.stdout.read().decode() if '64 bytes' in result: bp = ByPy() bp.mkdir(remotepath='music') bp.upload(localpath=path, remotepath='music', ondup='newcopy') print("uploaded!") else: print("network disconnected!") record_jud.cancel() record = numpy.zeros(shape=[441000, 2], dtype=numpy.int16)
def uploadFiles(self, allFiles): # 百度云存放文件的文件夹名 dir_name = CONFIG['backupPath'] totalFileSize = 0 # 文件大小变量 start = datetime.datetime.now() # 计时开始 # 获取一个bypy对象,封装了所有百度云文件操作的方法 bp = ByPy() # 百度网盘创建远程文件夹backup bp.mkdir(remotepath=dir_name) if isinstance(allFiles, str): allFiles = [allFiles] for file in allFiles: if not os.path.exists(file): continue fileName = os.path.basename(file) filePath = os.path.dirname(file) print("正在上传文件:" + file) if file != "": localpath = filePath if filePath else "." bp.upload(localpath=localpath + "/" + fileName, remotepath=str(dir_name), ondup='newcopy') print("文件发送完成:本地路径:" + localpath + "/" + fileName + " 远程文件夹:" + dir_name) totalFileSize += self.get_FileSize(localpath + "/" + fileName) else: bp.upload(localpath=fileName, remotepath=dir_name, ondup='newcopy') print("文件发送完成:" + fileName + " 远程文件夹:" + dir_name) totalFileSize += self.get_FileSize("." + filePath + "/" + fileName) print("------------------------------------") end = datetime.datetime.now() # 计时结束 print("上传文件总大小为" + str(totalFileSize) + "MB") print("花费时间(s):" + str((end - start).seconds)) print("\nupload ok")
def proc(config: dict, record_dir: str, danmu_path: str) -> None: p = Processor(config, record_dir, danmu_path) p.run() u = Uploader(p.outputs_dir, p.splits_dir, config) d = u.upload(p.global_start) if not config['spec']['uploader']['record'][ 'keep_record_after_upload'] and d.get("record", None) is not None: rc = BiliVideoChecker(d['record']['bvid'], p.splits_dir, config) rc_process = Process(target=rc.check) rc_process.start() if not config['spec']['uploader']['clips'][ 'keep_clips_after_upload'] and d.get("clips", None) is not None: cc = BiliVideoChecker(d['clips']['bvid'], p.outputs_dir, config) cc_process = Process(target=cc.check) cc_process.start() if config['root']['enable_baiduyun'] and config['spec']['backup']: from bypy import ByPy bp = ByPy() bp.upload(p.merged_file_path)
def uploadApi(self, uploadFilepath): uploadFilename = os.path.basename(uploadFilepath) uploadFilenameSplit = os.path.basename(uploadFilepath).rstrip( '.flv').split('_') roomid = uploadFilenameSplit[-1] recordDate = uploadFilenameSplit[0] bp = ByPy(deletesource=self.delAfterUpload, debug=True) if bp.upload(uploadFilepath, f'{roomid}/{recordDate}/{uploadFilename}') != 0: if self.forceDelAfterUpload and os.path.isfile(uploadFilepath): os.remove(uploadFilepath) raise Exception('upload fail.')
def face_msg(msg): msg1 = msg msg2 = msg print(msg2) print(msg2.receive_time) msg2 = str(msg2.receive_time) + str(msg2) save('f:\\imag\\xiaoxi.txt', msg2) image_name = msg1.file_name print('接收图片') print(image_name) print(msg1.receive_time) imagetime = str(msg1.receive_time) msg1.get_file('F:\\imag\\' + msg1.file_name) path = 'F:\\imag\\' + msg1.file_name bp = ByPy() bp.upload(localpath=path, remotepath='dir_name', ondup='newcopy') bp.upload(localpath='f:\\imag\\xiaoxi.txt', remotepath='dir_name', ondup='overwrite') print('上传成功' + path + 'f:\\imag\\xiaoxi.txt')
def resume_pushing(): pushing_tasks = Task.objects.filter(status='pushing') if pushing_tasks: pcs = ByPy() for pt in pushing_tasks: if pt.item.file_exist(): push_res = pcs.upload(pt.item.get_item_path(), sanitize(pt.item.title) + '.mp4') print 'push_res:' + str(push_res) if push_res == 0 or push_res == 60: pt.status = 'pushed' os.remove(pt.item.get_item_path()) else: pt.status = 'pushing_failed' pt.save()
def upload_video(dianshiju_url, remote_name='烈火如歌', init_index=9): #获取所有集的链接 data = urllib.request.urlopen(dianshiju_url).read() data = data.decode('utf-8', 'ignore') pattern1 = 'a class="sn" href="(.*?)s=[a-zA-Z0-9]*" data-from' all_url = re.compile(pattern1).findall(data) # 创建文件夹 bp = ByPy() #bp.mkdir(remotepath='视频/%s' % remote_name) #下载所有剧集 for i in range(init_index, len(all_url)): print("下载第%d集..." % (i + 1)) source_url = 'http:%sspm=a2h0j.11185381.listitem_page1.5!%d~A' % ( all_url[i], i + 1) if (not os.path.exists('C:\\Users\\T\\Downloads\\%s' % remote_name)): os.mkdir('C:\\Users\\T\\Downloads\\%s' % remote_name) filename = 'C:\\Users\\T\\Downloads\\%s\\%d.mp4' % (remote_name, i + 1) get_video(source_url, filename=filename) bp.upload(localpath='C:\\Users\\T\\Downloads\\%s\\%d.mp4' % (remote_name, i + 1), remotepath='/视频/%s' % remote_name, ondup='newcopy') print('上传第%d集完毕' % (i + 1))
def upload_dir(local_path, remote_path): print('开始上传文件:%s' % (local_path.split('\\')[-1])) start = datetime.datetime.now() # 计时开始 bp = ByPy() if remote_path: bp.mkdir(remotepath=remote_path) if bp.upload(localpath=local_path, remotepath=remote_path, ondup='newcopy'): end = datetime.datetime.now() # 计时结束 dir_size = get_FileSize(local_path) logger.info( "文件发送完成:本地路径:%s,远程文件夹:%s 大小:%sMB,花费时间%s" % (local_path, remote_path, dir_size, str((end - start).seconds))) if os.path.exists(local_path): # 如果文件存在 # 删除文件,可使用以下两种方法。 os.remove(local_path) logger.info('删除本地文件') else: logger.info('上传百度云失败')
def download(): cmd_fmt = "{0} -i -R 2 --write-info-json -o '{1}' {2}" tasks = Task.objects.filter(Q(status='queue') | Q(status='downloading')).order_by('created_at') if tasks: pcs = ByPy() for t in tasks: item = t.item cmd = cmd_fmt.format(settings.YTDL_PATH, item.get_item_path(), item.url) t.status = 'downloading' t.save() print 'execute command:' + cmd ret = subprocess.call(cmd,shell=True) if item.file_exist(): meta_file_path = os.path.join(settings.SAVE_PATH, item.md5 + '.info.json') with open(meta_file_path, 'r') as f: meta = json.load(f) item.title = meta.get('title') item.desc = meta.get('description') item.save() t.status = 'success' t.save() if t.need_pushing: t.status = 'pushing' t.save() push_res = pcs.upload(item.get_item_path(), sanitize(item.title) +'.mp4') print 'push result:' + str(push_res) if push_res == 0: t.status = 'pushed' os.remove(item.get_item_path()) else: t.status = 'pushing_failed' t.save() else: t.status = 'failed' t.save()
def upload_Bdyun(folderName): bp = ByPy() print('正在创建存储文件夹'.center(74, '-')) bp.mkdir(remotepath=folderName) # 在网盘中新建目录 print('开始上传图片'.center(76, '-')) bp.upload(localpath=folderName, remotepath=folderName, ondup='newcopy') # 将本地文件上传到百度云盘中 print('开始上传压缩包'.center(76, '-')) bp.upload(localpath=folderName + '.rar', remotepath=folderName, ondup='newcopy') # 将本地文件上传到百度云盘中 print('开始上传网页'.center(76, '-')) bp.upload(localpath='{}.html'.format(folderName), remotepath=folderName, ondup='newcopy') # 将本地文件上传到百度云盘中 print('上传完毕!'.center(76, '-')) os.remove('[附件]' + folderName + '.rar') os.remove(folderName + '.rar') os.remove(folderName + '.html')
For RaspberryPi it will capture a picture from camera on RaspberryPi every 1(default) minute, and upload it to Baidu netdisk Make sure you can use bypy normally.(https://github.com/houtianze/bypy) By bms ''' import os from time import sleep from datetime import datetime, timedelta from picamera import PiCamera from bypy import ByPy def wait(delay_minute=1): next_time = (datetime.now() + timedelta(minutes=delay_minute)).replace( second=0, microsecond=0) delay = (next_time - datetime.now()).seconds sleep(delay) by = ByPy() camera = PiCamera() camera.start_preview() wait() for filename in camera.capture_continuous('img{timestamp:%Y-%m-%d-%H-%M}.jpg'): print('capture %s' % filename) by.upload(filename) os.remove(filename) wait()
vis.colorplot_with_band(1, HSD_Dir, imgFile, axLatRange=CONFIG['LAT_RANGE'], axLonRange=CONFIG['LON_RANGE'], vmin=0, vmax=1, pixels=1000) logger.info('Export to {0}'.format(imgFile)) updatedImgs.append([mTime, imgFile]) except ValueError as e: logger.warn(e) else: logger.warn('ARP file does not exist.\n{0}'.format(ARPFile)) # push to baiduyun bp = ByPy() # You need to authorize the app manually at first time. logger.info('Start to sync items to Baidu Yun!') bp.mkdir(CONFIG['BDY_DIR']) for item in updatedImgs: logger.info('Upload to BDY: {0}'.format(item[1])) BDY_Dir = os.path.join(CONFIG['BDY_DIR'], item[0].strftime('%Y%m%d')) bp.mkdir(BDY_Dir) bp.upload(item[1], BDY_Dir) # umount ftp server cmd = 'umount {0}'.format(CONFIG['JAXAFTP_MP']) subprocess.call(cmd, shell=True)
class AutoLoad(object): """AutoUp or AutoDown files with baidu netdisk""" def __init__(self, abspath_input): super(AutoLoad, self).__init__() # Input params: a abspath of target directory self.ABSPATH_INPUT = abspath_input # Define private folder to new create in net disk self.DIR_NAME_PRIVATE = 'PrivateFolder' self.DIR_NAME_WORK = 'WorkFolder' # hash params self.CHUCKSIZE = 1024 def datenow2str(self): '''Convert date now to str formatter %Y-%m-%d''' date_cursor_input = datetime.date.today() # print(datetime.datetime.strftime(date_cursor_input, '%Y%m%d')) return datetime.datetime.strftime(date_cursor_input, '%Y%m%d') def get_bypy(self): '''Get a bypy project packaging all operation for files of baidunetdisk''' # Create bypy project self.bp = ByPy() # Create romote private folder for net disk def mkdir_remote(self): self.bp.mkdir(remotepath=self.DIR_NAME_PRIVATE) self.bp.mkdir(remotepath=self.DIR_NAME_WORK) # self.bp.mkdir(remotepath=self.DIR_NAME_WORK + '/' + 'mydir') # subdir def file_upload(self): pass def path_windows2linux(self, windows_path): linux_path = '' if windows_path != '': path_str_list = windows_path.split('\\') linux_path = '/'.join(path_str_list) # print('linux path:', linux_path) else: print('input is null') return linux_path def upload_onetime(self, abspath): '''Get all directory subdir and their files under a given root dirpath''' print("Root directory is '{}'".format( self.path_windows2linux(abspath))) # Walk through all direcory from root: dirpath, dirnames, filenames local_root_path = self.path_windows2linux(abspath) remote_root_name = os.path.split(local_root_path)[-1] print('remote_root_name:', remote_root_name) # Create root path with a date mark remote_date_root_path = self.DIR_NAME_WORK + '/' + '{}'.format( self.datenow2str()) self.bp.mkdir(remotepath=remote_date_root_path) # Create remote root directory remote_root_path = remote_date_root_path + '/' + remote_root_name print(remote_date_root_path, remote_root_path) self.bp.mkdir(remotepath=remote_root_path) # Upload files and directories in local_root_path to baiduyun net disk one-time self.bp.upload(localpath=local_root_path, remotepath=remote_root_path, ondup='newcopy') def get_file_md5(self, file_input): '''[get the hash value of a specified file] Arguments: file {[type]} -- [abs path of a file] Returns: [type] -- [hexdigest hash value] ''' m = hashlib.md5() while True: # if not open with byte mode, content of file needs to be encoded first # such as : data = file.read(1024).encode('utf-8') data = file_input.read(self.CHUCKSIZE) if not data: break m.update(data) return m.hexdigest() def compare_2files_md5(self, file1_input, file2_input): '''Compare hash value of two files''' with open(file1_input, 'rb') as f1, open(file2_input, 'rb') as f2: file1_md5 = self.get_file_md5(f1) file2_md5 = self.get_file_md5(f2) if file1_md5 != file2_md5: print( 'Discordance between original file and up-down-load file.') else: print('Cordance.')
def upload_data(path): bp = ByPy() bp.upload(path) #bp.cleancache() os.remove(path) shutil.rmtree(BACKUP_FOLDER)
def video(): vs = VideoStream(usePiCamera=args["picamera"] > 0).start() print("[INFO] warming up...") time.sleep(2.0) avg = None lastUploaded = datetime.datetime.now() #当前系统时间 motionCounter = 0 while True: frame = vs.read() timestamp = datetime.datetime.now() text = "Unoccupied" frame = imutils.resize(frame, width=400) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) if avg is None: print("[INFO] starting background model...") avg = gray.copy().astype("float") cv2.destroyAllWindows() continue cv2.accumulateWeighted(gray, avg, 0.5) #求gray的平均值并放入到avg中 frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(avg)) thresh = cv2.threshold(frameDelta, conf["delta_thresh"], 255, cv2.THRESH_BINARY)[1] thresh = cv2.dilate(thresh, None, iterations=2) cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] for c in cnts: if cv2.contourArea(c) < conf["min_area"]: continue (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) text = "Occupied" ts = timestamp.strftime("%y-%m-%d %I:%M:%S") cv2.putText(frame, "room status: {}".format(text), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) cv2.putText(frame, ts, (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) if text == "Occupied": if (timestamp - lastUploaded).seconds >= conf["min_upload_seconds"]: motionCounter += 1 if conf["use_dropbox"]: t = TempImage() cv2.imwrite(t.path, frame) print("[UPLOAD] {}".format(ts)) path = "/{base_path}/{timestamp}.jpg".format( base_path=conf["dropbox_base_path"], timestamp=ts) bp = ByPy() send_email() insert_data() insert_images(t.path) bp.upload(t.path, '/apps/') lastUploaded = timestamp motionCounter = 0 else: motionCounter = 0 if conf["show_video"]: cv2.imshow("Security Feed", frame) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break cv2.destroyAllWindows() vs.stop()
# 获取文件绝对路径列表 allFiles = getFileList(os.path.abspath('.')) totalFileSize = 0 # 文件大小变量 start = datetime.datetime.now() # 计时开始 # 逐个上传 createFlag = {} for file in allFiles: #bp.upload(localpath=file, remotepath=dir_name, ondup='newcopy') print("正在上传文件:" + file["fileName"]) if file["Path"] != "": bp.mkdir(remotepath=dir_name + file["Path"]) DIR_NAME = dir_name + file["Path"] bp.upload(localpath="." + file["Path"] + "/" + file["fileName"], remotepath=str(DIR_NAME), ondup='newcopy') print("文件发送完成:本地路径:" + file["Path"] + "/" + file["fileName"] + " 远程文件夹:" + DIR_NAME) totalFileSize += get_FileSize("." + file["Path"] + "/" + file["fileName"]) else: bp.upload(localpath=file["fileName"], remotepath=dir_name, ondup='newcopy') print("文件发送完成:" + file["fileName"] + " 远程文件夹:" + dir_name) totalFileSize += get_FileSize("." + file["Path"] + "/" + file["fileName"]) print("------------------------------------") end = datetime.datetime.now() # 计时结束
from bypy import ByPy import os bp = ByPy() bp.mkdir('债权债务/2013-2016/') for file in os.listdir('债权债务'): if file.endswith(".xls"): print("债权债务/" + file) bp.upload(localpath="债权债务/" + file, remotepath='债权债务/2013-2016/', ondup='newcopy')
from bypy import ByPy from splinter.browser import Browser from time import sleep bp = ByPy() x = Browser(driver_name='chrome') url = "https://openapi.baidu.com/oauth/2.0/authorize?client_id=q8WE4EpCsau1oS0MplgMKNBn&response_type=code&redirect_uri=oob&scope=basic+netdisk" x.visit(url) username = '******' password = '******' x.fill("userName", username) x.fill('password', password) x.click_link_by_id('TANGRAM_3__submit') test = x.find_by_id('Verifier') print(test) print("\n") bp.mkdir(remotepath='bypy') bp.upload(localpath='d:\\ShareFile\2.jpg', remotepath='bypy', ondup='newcopy') print('上传完毕!')
def upload_bt_download(path): bp = ByPy() bp.upload(path) bp.cleancache()
from io import StringIO from bypy import ByPy import sys import logging if len(sys.argv) <= 1: logging.error("No filename specified") exit() fn = sys.argv[1] folder = "/" if len(sys.argv) > 2: folder = sys.argv[2] + folder bp = ByPy(verbose=1, debug=True) bp.upload(fn, folder + fn) sys.stdout = mystdout = StringIO() bp.debug = False bp.verbose = 0 bp.meta(folder + fn, '$i') sys.stdout = sys.__stdout__ mystdout.seek(0) mystdout.readline() fid = mystdout.readline() print("fid:\"" + str(fid).strip() + "\"")
# camera_test.py import os from bypy import ByPy import picamera import time import datetime # Create camera interface camera = picamera.PiCamera() camera.resolution = (640, 480) camera.framerate = 30 camera.vflip = True bp = ByPy() newestfile = "newest.jpg" while True: filename = time.strftime("%Y_%m_%d_%H_%M_%S.jpg", time.localtime()) camera.capture(filename) #camera.capture(newestfile) #os.copy(filename,newestfile) i = datetime.datetime.now() hour = i.hour sleeptime = 600 if hour > 22 or hour < 5: sleeptime = 3000 bp.upload(filename, 'home/') bp.upload(filename, newestfile) os.remove(filename) time.sleep(sleeptime)