Esempio n. 1
0
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('上传百度云失败')
Esempio n. 2
0
class Upload(object):
    def __init__(self, medpath, panedirname):
        self.panedirname = panedirname
        self.medpath = medpath.rstrip('/') + '/'
        self.newdir, self.filelist = '', []
        self.bp = ByPy()

    def run(self):
        """
        该方法是遍历文件夹中所有的文件,然后逐一进行上传
        :return:
        """
        self.get_filelist(self.medpath)
        self.bp.mkdir(remotepath=self.panedirname)
        print "文件夹{}创建成功!".format(self.panedirname)
        time.sleep(2)
        print('Parent process %s.' % os.getpid())
        p = Pool(5)
        for m in self.filelist:
            ab_path = m.split(self.medpath)[1]
            if len(ab_path.split('/')) > 1:
                localpath = os.path.join(self.medpath, ab_path)
                remotepath = os.path.join(
                    self.panedirname,
                    '/'.join(ab_path.split('/')[:-1]).lstrip('/'))
                self.bp.mkdir(remotepath)
            else:
                localpath = os.path.join(self.medpath, ab_path)
                remotepath = self.panedirname
            print "start upload {} to /{}".format(localpath,
                                                  remotepath.lstrip('/'))
            p.apply_async(script_run, args=(
                localpath,
                remotepath,
            ))
        print 'Waiting for all subprocesses done...'
        p.close()  # 关闭不在添加子进程
        p.join()
        print 'All subprocesses done.'

    def get_filelist(self, dir_path):
        """
        遍历文件夹中所有的文件
        :param dir_path:
        :return:
        """
        self.newdir = dir_path
        if os.path.isfile(dir_path):
            self.filelist.append(dir_path)
        elif os.path.isdir(dir_path):
            for s in os.listdir(dir_path):
                self.newdir = os.path.join(dir_path, s)
                self.get_filelist(self.newdir)
Esempio n. 3
0
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')  # 上传图片
Esempio n. 4
0
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')
Esempio n. 5
0
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)
Esempio n. 6
0
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('上传百度云失败')
Esempio n. 7
0
    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")
Esempio n. 8
0
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')
Esempio n. 9
0
from bypy import ByPy
import os
import time
import datetime
import threading

# 百度云存放文件的文件夹名
dir_name = "ByPy-test"

# 获取一个bypy对象,封装了所有百度云文件操作的方法
bp = ByPy()
# 百度网盘创建远程文件夹bypy-test
bp.mkdir(remotepath=dir_name)


# 函数作用:文件中的 \ 改为 /
# 函数输入:文件绝对路径
# 输出:文件绝对路径添加转义符后的结果
def changePath(filePath):
    path = ""
    for i in range(len(filePath)):
        if filePath[i] != "\\":
            path += filePath[i]
        else:
            path += "/"
    return path


# 根据当前路径和文件夹路径得到相对路径
def relPath(filePath, topDir):
    relativepath = ""
Esempio n. 10
0
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('上传完毕!')
Esempio n. 11
0
            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)
Esempio n. 12
0
    def on_btn_click(self):
        self.up = UL()
        self.up.show()

    def Exit(self):
        self.close()

    def Mini(self):
        self.showMinimized()


# 获取一个bypy对象,封装了所有百度云文件操作的方法
bp = ByPy()
print(bp.list(""))
'''
# 百度网盘创建文件夹zhoulong
bp.mkdir(remotepath = 'Jizy')
#上传文件至文件夹
# upload中参数代表复制文件,默认值为'overwrite',指定'newcopy'不会覆盖重复文件
bp.upload(localpath= r'上传文件绝对路径', remotepath= 'zhoulong', ondup='newcopy')
print('上传完成!!')
bp.download(remotepath = 'zhoulong', localpath = r'下载文件输出文件夹')
print('下载完成!!')

print("ST")
bp.download(remotepath="骆驼祥子   读书笔记 7.pptx",localpath=r"F:\\Baidu\\")
print("Done")'''
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    ui = MainUI()
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.')
Esempio n. 14
0
from bypy import ByPy
import os
import time


channel_name = 'PHP Tutorials'  # change wow_english Business English Pod
start_time = time.time()
download_path = os.getcwd() + '\\' + '2_download' + '\\' + channel_name
print(download_path)
bp = ByPy()
bp.mkdir(remotepath='youtube')  #在网盘中新建目录
bp.syncup(download_path,'youtube') #将本地文件上传到百度云盘中
print('上传完毕!')
print((time.time() - start_time) / 60)
Esempio n. 15
0
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')
Esempio n. 16
0
def create_baidu_dir():
    bp = ByPy()
    for i in range(810020001, 810020026):
        dir_name = '/xiaoshandata/' + str(i)
        bp.mkdir(remotepath=dir_name)
Esempio n. 17
0
from bypy import ByPy
import os
import time
import datetime
import threading

# 百度云存放文件的文件夹名
dir_name = "ByPy-test"

# 获取一个bypy对象,封装了所有百度云文件操作的方法
bp = ByPy()
# 百度网盘创建远程文件夹bypy-test
bp.mkdir(remotepath=dir_name)


# 函数作用:文件中的 \ 改为 /
# 函数输入:文件绝对路径
# 输出:文件绝对路径添加转义符后的结果
def changePath(filePath):
    path = ""
    for i in range(len(filePath)):
        if filePath[i] != "\\":
            path += filePath[i]
        else:
            path += "/"
    return path


# 根据当前路径和文件夹路径得到相对路径
def relPath(filePath, topDir):
    relativepath = ""