my python script (1) ---------create model script file

本文介绍了一个使用Python编写的简单工具,该工具可以根据用户输入的文件路径自动生成包含基本Python代码的脚本文件。它首先检查并创建指定的目录路径,然后在目标位置创建Python文件,并写入初始化代码。

# my  python script (1)

#  to create script file 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os,subprocess,sys

child = subprocess.Popen('which python',stdout = subprocess.PIPE,shell=True)
(pypath,error) = child.communicate()
pypath = pypath.strip('\n')

myfile = raw_input('please input file name (like home/test.py)')
if myfile:
    (path,filename) = os.path.split(myfile)
    if path:
        print 'check dir path ...'
        if os.path.exists(path):
            print 'dir already exists!'
        else:    
            print 'dir: %s does not exist!' % path
            print 'create dir: %s ...' % path
            try:
                os.makedirs(path)
                print 'dir: %s is created successfully!' % path    
            except Exception ,e:
                print 'exception occur while try to create dirs %s' % path
                print e
    else:
        pass
else:
    sys.exit('input is none!')

print 'create script file: %s ...' % filename
try:
    f = open(myfile,'w')
    f.write('#!'+ pypath + '\n')
    f.write('#! -*- coding:utf-8 -*-')
    f.write('\n')
    f.write('\n')
    f.write('if __name__ == '+ "'__main__':\n")
    f.write('    print "hello world!"\n')
    f.close()
    print 'script is created successfully!'
except Exception,e:
    print 'exception occur while try to write file: %s ' % filename
    print e

 

转载于:https://www.cnblogs.com/ct-blog/p/5496818.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值