python
  • database
  • shell
  • beagleboneblack
  • 2017-04-27 130 views 0 likes 
    0

    我目前正在尝试通过使用python中的os.system方法来运行shell脚本。调用python来运行shell脚本

    Python代码:

    file = open("History.txt","w") 
    file.write(history) 
    os.system('./TFPupload.sh') 
    

    shell脚本代码:

    #!/bin/sh 
    
    HOST="ftp.finalyearproject95.com" 
    USER='*****' 
    PASSWD='*****' 
    FILE='History.txt' 
    
    ftp -n $HOST <<END_SCRIPT 
    quote USER $USER 
    quote PASS $PASSWD 
    put $FILE 
    quit 
    END_SCRIPT 
    
    echo ">>>uploaded<<<\n" 
    
    exit 0 
    

    起初,当我试图通过一个运行Python代码和shell脚本一个它完美的作品。但是,当我尝试使用python运行shell脚本时,上载的文件是一个空文件,而不是上载包含数据的“History.txt”文件到数据库中。当我使用'nano History.txt'检查时,它确实包含数据,只有当它将文本文件传递到数据库时才会是空的。为什么?

    +1

    您需要关闭或刷新打开的文件,以确保书面写入磁盘的内容。 – metatoaster

    +0

    感谢您的帮助。它真的解决了我的问题 – beginner

    回答

    0

    使用With语句尽可能地打开文件。

    with open("History.txt","w") as file : 
        file.write(history) 
    
    os.system('./TFPupload.sh') 
    

    with声明负责自行关闭fd。

    一些参考:What is the python "with" statement designed for?

    +0

    这也是一个很好的建议。感谢您的帮助 – beginner

    相关问题