今天发现python windows运行正常,linux下异常

41 篇文章 2 订阅
11 篇文章 0 订阅


好久没使用Python,基本上以前学的一点皮毛也忘记完了。今天想在linux中处理xls文件,然后存到数据库中,想用简单的Python来处理。好久没用了,加上用的Python3.5.2新版本,简单的事情还真废了不少劲。具体工作是linux下某个目录,会有文件定期穿上来(15分钟一次),对其中最新的一个xls文件进行处理,读取数据到mysql存储,然后删除目录下所有文件。程序每10分钟运行一次。windows里程序调试完了,但是传到linux上运行不正常。

首先文件编辑后提示不认识的编码utf-8,应为我的linux系统默认的是中文gb18030

python 文件中用的utf-8,修改成gb18030就OK了,这个问题解决了有遇到个奇葩事情。

/home/pon目录下木有xls文件的时候要报错,有的时候就不报错,我明天添加了判断语句

l=os.listdir(path) len(l)>0 才执行,搞了很久没解决,后然实在不行了,把l这个数组打印出来看,打印出来吓一跳,目录下没文件,怎么显示有四个文件,shell 下用ls -al 一看,原来真有几个隐藏文件。好吧增加个工作,先判断下目录下有没有.xls文件。网上看了下,没找到简单的方法,自己想了个,把l这个数组转换成字符串,然后判断字符串中是否包含.xls,就这样坚决了。

最后就是让代码在后台运行,直接 在运行命令后加& 但是用jobs命令看,发现stoped,貌似程序没运行了。想起还是用screen -S 新建个窗口,运行代码,然后Ctrl+a d detach这个窗口,让他后台运行。搞了几个小时终于搞定了。


Python代码如下,差不多忘记完了。

#--coding:gb18030--
#filename:man_pon_alarms.py
import pymysql.cursors
import xlrd
import os
import time
import glob
# Connect to the mysql database
#import os,os.path,datetime
def main():
    base_dir=r"/home/pon/"
    l=os.listdir(base_dir)   
    #confirm the dirpath has xls file
    if (''.join(l).find(".xls"))>0:     
        l.sort(key=lambda fn: os.path.getmtime(base_dir+fn) if not os.path.isdir(base_dir+fn) else 0)
        workbook = xlrd.open_workbook(base_dir+l[-1])
        worksheet1 = workbook.sheets()[0]
        num_cols = worksheet1.ncols
        num_rows = worksheet1.nrows
        num_cols = worksheet1.ncols
        connection = pymysql.connect(host='175.155.1.3',
                                         user='popon',
                                         password='pon-pop-3',
                                         db='db_pon_alarm',
                                         charset='utf8mb4',
                                         cursorclass=pymysql.cursors.DictCursor)
        try:
                with connection.cursor() as cursor:
                    for rown in range(3,num_rows-1):
                        # Create a new record
                        sql = "INSERT INTO tb_PonAlarms(NetCell, NetCellLocal,AlarmCode,AlarmNote,AlarmTime,AlarmText,NetIP) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')"
                        cursor.execute(sql%(worksheet1.cell_value(rown,2), worksheet1.cell_value(rown,3),worksheet1.cell_value(rown,6),worksheet1.cell_value(rown,7),worksheet1.cell_value(rown,8),worksheet1.cell_value(rown,11),worksheet1.cell_value(rown,23)))
                        connection.commit()
                        print("read alarms succed")
        finally:
                    connection.close()
                    for filename in os.listdir(base_dir):
                        if '.xls' in filename:
                             os.remove(base_dir+filename)


def timer(n):
    while True:
        print('program round start at:',time.strftime('%Y-%m-%d %X',time.localtime()))
        main()
        print('program round finished at:',time.strftime('%Y-%m-%d %X',time.localtime()))
        print('next round will start after %d second'%n)
        time.sleep(n)

if __name__ == '__main__':
    timer(600)


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 Python 中的 ftplib 模块来实现这个功能。 以下是一个简单的示例代码: ``` import ftplib ftp = ftplib.FTP("ftp.example.com") ftp.login("username", "password") ftp.cwd("/") filename = "file.txt" ftp.retrbinary("RETR " + filename, open(filename, "wb").write) ftp.quit() ``` 需要注意的是,在这个示例代码中,需要将 `ftp.example.com` 替换为您的 FTP 服务器的地址,`username` 和 `password` 替换为您的 FTP 账户的用户名和密码。另外,如果要从 LinuxWindows 传输文件,您需要确保您的 FTP 服务器正在运行并且可以被连接。 ### 回答2: 在Python中使用ftplib库可以轻松实现通过FTP从LinuxWindows传输文件的功能。以下是一个简单的示例代码: ```python import ftplib def ftp_transfer(source_path, destination_path, hostname, username, password): try: # 连接FTP服务器 ftp = ftplib.FTP(hostname) ftp.login(username, password) # 切换到目标目录 ftp.cwd(destination_path) # 以二进制模式打开本地文件 with open(source_path, 'rb') as file: # 将文件上传到服务器 ftp.storbinary('STOR ' + destination_path, file) ftp.quit() print("文件传输成功") except ftplib.all_errors as e: print("文件传输失败:", e) # 调用函数进行文件传输 source_path = "/path/to/source/file.txt" destination_path = "/path/to/destination/file.txt" hostname = "FTP服务器IP地址" username = "FTP登录用户名" password = "FTP登录密码" ftp_transfer(source_path, destination_path, hostname, username, password) ``` 请注意将示例中的 `source_path`、`destination_path`、`hostname`、`username`和`password` 替换为实际的值。示例中的代码连接到FTP服务器,将本地的`source_path`文件传输到FTP服务器的`destination_path`路径下。 ### 回答3: 当使用Python与FTP协议进行文件传输时,我们需要使用ftplib库。下面是一个使用ftplib库实现从LinuxWindows传输文件的示例代码: ```python import ftplib def transfer_file(hostname, username, password, source_file, destination_file): # 建立FTP连接 ftp = ftplib.FTP(hostname) ftp.login(username, password) # 初始化传输模式为二进制 ftp.set_pasv(True) # 打开本地文件作为二进制读取 with open(source_file, 'rb') as file: # 上传文件到FTP服务器 ftp.storbinary('STOR ' + destination_file, file) # 关闭FTP连接 ftp.quit() # 使用示例 hostname = 'ftp.example.com' # FTP服务器的地址 username = 'your_username' # FTP登录用户名 password = 'your_password' # FTP登录密码 source_file = '/path/to/local/file.txt' # 本地文件路径 destination_file = '/path/to/remote/file.txt' # 远程文件路径 transfer_file(hostname, username, password, source_file, destination_file) ``` 在上面的代码中,我们首先使用ftplib库建立与FTP服务器的连接,然后登录服务器并设置传输模式为二进制。接下来,我们打开本地文件作为二进制文件,并使用FTP的storbinary()方法将文件上传到FTP服务器上的指定路径。最后,我们关闭与FTP服务器的连接。 请注意,以上示例仅适用于LinuxWindows操作系统传输文件。如果需要进行其他类型的文件传输,请根据具体需求进行相应的代码修改。另外,在实际使用中,还应该添加适当的错误处理和异常捕获机制来保证操作的稳定性和安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值