Ejemplo n.º 1
1
	def import_csv(self, username, userpass, filestream):
		retCode = True
		import_xml_command = sh.Command("/usr/share/ds-matricula-plugin/matricula-common-scripts/1-itaca2mysql")
		# set a temporary filename
		TMP_CSV = tempfile.mkstemp()[1]
		TMP_CSV2 = tempfile.mkstemp()[1]
		if self._put_file(TMP_CSV, filestream):
			TMP_XML = tempfile.mkstemp()[1]
			sh.sed(sh.iconv("-f", "ISO-8859-15", "-t", "UTF-8", TMP_CSV), "-e", "1{s%[[:blank:]]%%g;s%\.%%g;s%[ñÑ]%n%g;s%.*%\L&%}", _out=TMP_CSV2)

			if self._csv2xml(TMP_CSV2, TMP_XML):
				try:
					import_xml_command(TMP_XML)
				except ErrorReturnCode:
					# some error happened
					retCode = False

			os.remove(TMP_XML)
		os.remove(TMP_CSV)
		os.remove(TMP_CSV2)
		return retCode
Ejemplo n.º 2
0
def main(logger=mylog.default_logger()):
    # load arguments and logger
    arguments = docopt(__doc__, version='0.0')
    # print arguments
    # script self name
    self_name=os.path.basename(sys.argv[0])
    # log
    # logfile=self_name.replace('py','log')
    # logger=set_mylogger(arguments,logfile)
    # load config
    # main_config=load_config('.ll')

    # set filename varibles
    # main_title=os.path.basename(os.getcwd())
    # markdown_file_name=os.path.join(os.getcwd(),'build',main_title+'.markdown')
    # docx_file_name=main_title+'.docx'
    # rtf_file_name=main_title+'.rtf'

    md_pattern=re.compile(r'\.md$')

    markdown_file_name=arguments.get('<filename>')
    if markdown_file_name:
        if os.path.isdir(markdown_file_name):
            walk_sed(markdown_file_name)
        else:
            sh.sed('-i','-e','s/^#//',markdown_file_name)
            # sh.sed('-i','-e','s/^#/'+'#/',markdown_file_name)
    else:
        walk_sed('.')
Ejemplo n.º 3
0
def env_init(site_name=SITE_NAME):
    '''Initialize with this site hostname.'''
    print(green("Initializing new site configuration..."))

    #
    # Generate secret key and update config file
    #
    import random
    import string

    CHARS = string.ascii_letters + string.digits
    SECRET_KEY = "".join([random.choice(CHARS) for i in range(50)])

    print(blue("Configuring the secret key..."))
    os.chdir(PROJ_DIR)
    try:
        sh.sed("-i ",
               "s/SECRET_KEY *=.*/SECRET_KEY = '{0}'/g".format(SECRET_KEY),
               "{0}/config.py".format(APP_NAME))
    except sh.ErrorReturnCode:
        print(red("Could not configure SECRET_KEY for config.py"))
        exit(1)

    #
    # Set the site name, the user defined site hostname
    #
    print(blue("Configuring the SITE_NAME '{0}'.".format(site_name)))
    try:
        sh.sed("-i ",
               "s/SITE_NAME *=.*/SITE_NAME = '{0}'/g".format(site_name),
               "{0}/config.py".format(APP_NAME))
    except sh.ErrorReturnCode:
        print(red("Could not configure SITE_NAME for config.py"))
        exit(1)
Ejemplo n.º 4
0
def check_upgrade():
        server_file = curl(PIFM_HOST + '/client_agent/pifm_agent.py')
        server_sum = awk(
                        md5sum(
                            grep(server_file, '-v', '^PIFM_HOST')
                        ), '{print $1}'
        )

        local_sum = awk(
                        md5sum(
                            grep('-v', '^PIFM_HOST', OUR_SCRIPT)
                        ), '{print $1}'
        )

        if str(server_sum) != str(local_sum):
            logging.info(
                "server: {server}, local: {local}, should update.".format(
                    server=server_sum,
                    local=local_sum
                )
            )
            with open(TMP_SCRIPT, 'w') as f:
                f.write(str(server_file))
            sed('-i',
                "0,/def/ s#http://pi_director#{myhost}#".format(myhost=PIFM_HOST),
                OUR_SCRIPT
                )
            status = python('-m', 'py_compile', TMP_SCRIPT)
            if (status.exit_code == 0):
                shutil.copy(TMP_SCRIPT, OUR_SCRIPT)
                os.chmod(OUR_SCRIPT, 0755)
                sys.exit(0)
    def html_output(self):
        ext = '.html'
        today = datetime.date.today().isoformat()
        sha = self.test_file + ".html.sha"
        # cannot recover if generating html fails
        options = (['--zip'] + self.options
                   + ['-f', 'html', self.test_file,
                      self.test_out + ext + '.zip'])
        try:
            self.gdoc_to(*options,
                         _err=self.test_err + ".html.log")
            # XXX it hangs without -n, didn't have time to figure out why
            out_dir = os.path.dirname(self.test_out)
            sh.unzip('-n', '-d', out_dir, self.test_out + ext + '.zip')
            sh.sed('-i', '-e', 's/%s/TODAYS_DATE/g' % today,
                   self.test_out + ext)
            test_result = slurp('%s.html' % self.test_out)
        except ErrorReturnCode as e:
            self.say(red("gdoc-to failed: {}. See {}.html.log"),
                     e, self.test_err)
            self.say(red("Ran in {}"), os.getcwd())
            self.failed = True
            sh.rm('-f', sha)
            return
        try:
            html5check(self.test_out + ext,
                       _out=self.test_out + ".html.errors")
        except ErrorReturnCode:
            self.say(red("Test output did not validate as XHTML5!"))
            self.say(red("\tSee {}.html.errors"), self.test_out)
            self.failed = True

        if test_result != slurp(self.test_file + ext):
            # the file changed, but the change might be okay
            spit(self._canonical_body(self.test_out + ext),
                 self.test_out + ".body")
            spit(self._canonical_body(self.test_file + ext),
                 self.test_out + ".canon.body")

            if (slurp(self.test_out + '.body')
                    == slurp(self.test_out + '.canon.body')):
                self.say(yellow("File changed. Updating canonical file."))
                sh.cp(self.test_out + ext, self.test_file + ext)
            else:
                self.say(red("HTML body changed!"))
                self.say(red("\tSee {}.*"), fail_path(self.test_name))
                sh.cp(self.test_out + ext, fail_path(self.test_name + ext))
                sh.diff('-u', self.test_file + ext, self.test_out + ext,
                        _out=fail_path(self.test_name + ".html.diff"),
                        _ok_code=[0, 1])
                sh.cp(self.test_out + ".body",
                      fail_path(self.test_name + ".body"))
                sh.cp(self.test_out + ".canon.body",
                      fail_path(self.test_name + ".body.expected"))
                sh.diff('-u', self.test_out + ".canon.body",
                        self.test_out + ".body",
                        _out=fail_path(self.test_name + '.body.diff'),
                        _ok_code=[0, 1])
                self.failed = True
Ejemplo n.º 6
0
def walk_sed(dirname):
    md_pattern=re.compile(r'\.md$')
    list_dirs=os.walk(dirname)
    for root,dirs,files in list_dirs:
        for f in files:
            if md_pattern.search(f):

                sh.sed('-i','-e','s/^#//',os.path.join(root, f))
Ejemplo n.º 7
0
def test_i18n(journalist_app, config):
    # Then delete it because using it won't test what we want
    del journalist_app

    sources = [
        os.path.join(TESTS_DIR, "i18n/code.py"),
        os.path.join(TESTS_DIR, "i18n/template.html"),
    ]

    i18n_tool.I18NTool().main([
        "--verbose",
        "translate-messages",
        "--mapping",
        os.path.join(TESTS_DIR, "i18n/babel.cfg"),
        "--translations-dir",
        config.TEMP_DIR,
        "--sources",
        ",".join(sources),
        "--extract-update",
    ])

    pot = os.path.join(config.TEMP_DIR, "messages.pot")
    pybabel("init", "-i", pot, "-d", config.TEMP_DIR, "-l", "en_US")

    for (l, s) in (
        ("fr_FR", "code bonjour"),
        ("zh_Hans", "code chinese"),
        ("ar", "code arabic"),
        ("nb_NO", "code norwegian"),
        ("es_ES", "code spanish"),
    ):
        pybabel("init", "-i", pot, "-d", config.TEMP_DIR, "-l", l)
        po = os.path.join(config.TEMP_DIR, l, "LC_MESSAGES/messages.po")
        sed("-i", "-e",
            '/code hello i18n/,+1s/msgstr ""/msgstr "{}"/'.format(s), po)

    i18n_tool.I18NTool().main([
        "--verbose",
        "translate-messages",
        "--translations-dir",
        config.TEMP_DIR,
        "--compile",
    ])

    fake_config = SDConfig()
    fake_config.SUPPORTED_LOCALES = [
        "ar", "en_US", "fr_FR", "nb_NO", "zh_Hans"
    ]
    fake_config.TRANSLATION_DIRS = Path(config.TEMP_DIR)

    # Use our config (and not an app fixture) because the i18n module
    # grabs values at init time and we can't inject them later.
    for app in (journalist_app_module.create_app(fake_config),
                source_app.create_app(fake_config)):
        with app.app_context():
            db.create_all()
        assert list(i18n.LOCALES.keys()) == fake_config.SUPPORTED_LOCALES
        verify_i18n(app)
Ejemplo n.º 8
0
    def _add_description(self):
        """ adds description to control file"""
        if not self.description or not len(self.description) <= 60:
            logger.warning('bad description, using default pattern')
            self.description = '{} Package'.format(self.package_name)

        sh.sed('-i', r'/^Description/c\\Description: {}'
               .format(self.description),
               self.debian_package_path + '/debian/control').wait()
Ejemplo n.º 9
0
    def _add_deb_dependencies(self):
        """ adds deb dependencies to control file """
        if self.dependencies:
            debian_dependencies = self.dependencies_to_debian_format(
                self.dependencies)
            dependencies_str = ', '.join(debian_dependencies)

            sh.sed('-i', r'/^Depends/c\\Depends: ${{misc:Depends}}, {}'
                   .format(dependencies_str),
                   self.debian_package_path + '/debian/control').wait()
Ejemplo n.º 10
0
def add_pr_to_checkout(repo, pr_id, head_sha1, pr_branch, spec):
    sh.curl(
        '-s', '-k', '-L',
        "https://github.com/crowbar/%s/compare/%s...%s.patch" % (
            repo, pr_branch, head_sha1),
        '-o', 'prtest.patch')
    sh.sed('-i', '-e', 's,Url:.*,%define _default_patch_fuzz 2,',
           '-e', 's,%patch[0-36-9].*,,', spec)
    Command('/usr/lib/build/spec_add_patch')(spec, 'prtest.patch')
    iosc('vc', '-m', "added PR test patch from %s#%s (%s)" % (
        repo, pr_id, head_sha1))
Ejemplo n.º 11
0
def create(template, project_name):
    templates = get_templates()
    if template not in templates:
        click.echo('%s template not found' % template, err=True)
        return
    project_dir = './' + project_name
    sh.mkdir('-p', project_dir)
    sh.cp('-rf', os.path.join(HERE, 'templates/simple/'), project_dir)
    for f in sh.find(project_dir, '-name', '*.py'):
        sh.sed('-i', '', '-e', 's/%s/%s/g' % ('proj', project_name), f.strip())
    sh.mv(os.path.join(project_dir, 'proj'),
          os.path.join(project_dir, project_name))
Ejemplo n.º 12
0
 def phred_13_to_18_sed(self, new_path=None, in_place=True):
     """Illumina-1.3 format conversion to Illumina-1.8 format via sed (faster)."""
     # String #
     sed_command = r"""4~4y/@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghi/!"#$%&'\''()*+,-.\/0123456789:;<=>?@ABCDEFGHIJ/"""
     # Faster with bash utilities #
     if in_place is True:
         sh.sed('-i', sed_command, self.path)
         return self
     # New file #
     if new_path is None: new_fastq = self.__class__(new_temp_path())
     else:                new_fastq = self.__class__(new_path)
     sh.sed(sed_command + " " + new_fastq, self.path)
     return new_fastq
Ejemplo n.º 13
0
def migrate():
    print("Migrating from previous version")

    for api in APIS[0:3]:
        print("Migrating {} database...".format(api['name']))
        name = api['bbdd']
        dump_file_bk = '/tmp/{}_dump.sql'.format(api['name'])
        dump_file = '/tmp/{}_dump_cp.sql'.format(api['name'])

        cp(dump_file_bk, dump_file)

        sed('-i', "s|:([0123456789\.]*)||g", dump_file)

        mysql('-u', DBUSER, '-p{}'.format(DBPWD), '-h', DBHOST, '-P', DBPORT, '-e', "DROP DATABASE {}".format(name))
        mysql('-u', DBUSER, '-p{}'.format(DBPWD), '-h', DBHOST, '-P', DBPORT, '-e', "CREATE DATABASE {}".format(name))

        mysql('-u', DBUSER, '-p{}'.format(DBPWD), '-h', DBHOST, '-P', DBPORT, name, '-e', "source {}".format(dump_file))

        if api['name'] == 'inventory':
            conn = pymysql.connect(host=DBHOST, port=DBPORT, user=DBUSER, passwd=DBPWD, db=api['bbdd'])
            cur = conn.cursor()
            cur.execute("select * from PRODUCT_CHARACTERISTIC")

            results = cur.fetchall()
            for res in results:
                sp_name = res[2].split(' ')

                cur.execute(
                    "SELECT PRODUCT_OFFERING.ID FROM PRODUCT INNER JOIN PRODUCT_OFFERING ON PRODUCT.PRODUCT_OFFERING_PRODUCT_HJID=PRODUCT_OFFERING.HJID WHERE PRODUCT.ID={}".format(res[4]))

                off_id = cur.fetchone()[0]
                new_ids = None
                if (res[2].lower().endswith('asset type') or res[2].lower().endswith('media type')) and len(sp_name) > 2:
                    new_ids = _process_ids(sp_name[0:-2], off_id)
                    name = '{} {}'.format(sp_name[-2], sp_name[-1])

                elif res[2].lower().endswith('location') and len(sp_name) > 1:
                    new_ids = _process_ids(sp_name[0:-1], off_id)
                    name = sp_name[-1]

                if new_ids is not None:
                    # Update characteristic name
                    new_name = ' '.join(new_ids)
                    new_name = new_name + ' ' + name

                    cur.execute("UPDATE PRODUCT_CHARACTERISTIC SET NAME_ = '{}' WHERE HJID={}".format(new_name, res[0]))

            conn.commit()
            conn.close()

        print("Database {} migrated".format(api['name']))
Ejemplo n.º 14
0
def setupX11Authorization(xauthFile, display):
    try:
        sh.touch(xauthFile)
    except:
        print("touch failed")
    sh.xauth(sh.sed(sh.xauth("nlist", display), "-e", 's/^..../ffff/'), "-f",
             xauthFile, "nmerge", "-")
Ejemplo n.º 15
0
 def remove_trailing_stars(self, new_path=None, in_place=True, check=False):
     """Remove the bad character that can be inserted by some programs at the
     end of sequences."""
     # Optional check #
     if check and int(sh.grep('-c', '\*', self.path, _ok_code=[0,1])) == 0: return self
     # Faster with bash utilities #
     if in_place is True:
         sh.sed('-i', 's/\*$//g', self.path)
         return self
     # Standard way #
     if new_path is None: new_fasta = self.__class__(new_temp_path())
     else:                new_fasta = self.__class__(new_path)
     new_fasta.create()
     for seq in self: new_fasta.add_str(str(seq.seq).rstrip('*'), seq.id)
     new_fasta.close()
     return new_fasta
Ejemplo n.º 16
0
def dfs_dir(root_dir,markdown_file,level,logger=mylog.default_logger()):
    # generate the filelist, ignore the hidden files.
    hiden_file=re.compile(r'^\.|main_title\.md|\.synopsis$|\.markdown')
    effective_file=re.compile(r'(^.*_+|^[0-9]*_*)(.*)\.md$')
    efflists=[ filename for filename in os.listdir(root_dir) if  effective_file.match(filename)]
    efflists_title=[ effective_file.match(filename).group(2) for filename in os.listdir(root_dir) if  effective_file.match(filename)]

    alllists=[ filename for filename in os.listdir(root_dir) if not hiden_file.match(filename)]

    #
    for filename,title in zip(efflists,efflists_title):
        path = os.path.join(root_dir, filename)
        # print logger
        logger.debug(filename+title)


        # write the file content according to level
        #TODO: 文件夹的处理,文件夹名+.md, .synopsis的处理
        if os.path.isdir(path):
            markdown_file.write('#'*level+title)
            markdown_file.write('\n')
            # if os.path.exists(str(path)+'/00.content'):
                # markdown_file.write(str(sh.cat(path+'/00.content'))+'\n')
            dfs_dir(path, markdown_file, level+1)
        else:
            if title:
                markdown_file.write('#'*level+title)
            markdown_file.write('\n')
            markdown_file.write(str(sh.sed('s/^#/'+'#'*level+'#/',path)))
Ejemplo n.º 17
0
def _change_vim_color_scheme(colorscheme, background):
    vimrc_path = os.path.expanduser('~/.vimrc')

    sed_cmd = 's/colorscheme {old_scheme}/colorscheme {new_scheme}/g'
    sed_cmd = sed_cmd.format(old_scheme=colorscheme[0], new_scheme=colorscheme[1])
    sed('-i', sed_cmd, vimrc_path)

    sed_cmd = 's/background={old_bg}/background={new_bg}/g'
    sed_cmd = sed_cmd.format(old_bg=background[0], new_bg=background[1])
    sed('-i', sed_cmd, vimrc_path)

    change_color = '<Esc>:set background={new_bg}<CR>:colorscheme {new_scheme}<CR>'
    change_color = change_color.format(new_bg=background[1], new_scheme=colorscheme[1])
    try:
        for server in vim('--serverlist'):
            vim('--servername', server.strip(), '--remote-send', change_color)
    except ErrorReturnCode_1:
        pass
Ejemplo n.º 18
0
    def capture_screen(self):
        """
        Use adb shell screencap
        :return: CV2Img
        """
        img = CV2Img()
        result = sed(adb("shell", "screencap", "-p"), 's/\r$//')

        return img.load_binary(result.stdout)
Ejemplo n.º 19
0
def device_list():
    """
    Get udid from iPhone and iPad plugged into the computer
    Returns a list
    """

    # TODO: separate iPhone and iPad
    raw = sh.sed(sh.system_profiler("SPUSBDataType"), "-n", "-e",
                 '/iPad/,/Serial/p', "-e", '/iPhone/,/Serial/p')
    devices = sh.awk(
        sh.grep(raw, "Serial Number:"), "-F", ": ", "{print $2}").split('\n')
    return [device for device in devices if device]
Ejemplo n.º 20
0
 def build_arch(self, arch):
     options_iphoneos = (
         "-isysroot {}".format(arch.sysroot),
         "-DOPENSSL_THREADS",
         "-D_REENTRANT",
         "-DDSO_DLFCN",
         "-DHAVE_DLFCN_H",
         "-fomit-frame-pointer",
         "-fno-common",
         "-O3"
     )
     build_env = arch.get_env()
     target = arch_mapper[arch.arch]
     shprint(sh.env, _env=build_env)
     sh.perl(join(self.build_dir, "Configure"),
             target,
             _env=build_env)
     if target == 'iphoneos-cross':
         sh.sed("-ie", "s!^CFLAG=.*!CFLAG={} {}!".format(build_env['CFLAGS'],
                " ".join(options_iphoneos)),
                "Makefile")
         sh.sed("-ie", "s!static volatile sig_atomic_t intr_signal;!static volatile intr_signal;! ",
                "crypto/ui/ui_openssl.c")
     else:
         sh.sed("-ie", "s!^CFLAG=!CFLAG={} !".format(build_env['CFLAGS']),
                "Makefile")
     shprint(sh.make, "clean")
     shprint(sh.make, "-j4", "build_libs")
Ejemplo n.º 21
0
def get_container_info():
    container_info = {}

    try:
        container_info['container_name'] = tail(sed(grep(cat('/proc/self/cgroup'), 'docker'), 's/^.*\///'), '-n1')
    except:
        container_info['container_name'] = 'unknown'

    try:
        container_info['app_version'] =  open('version', 'r').read()
    except:
        container_info['app_version'] = 'unknown'


    return container_info
Ejemplo n.º 22
0
    def set_hostname(self, hostname):
        """Update hostname

            Args:
                hostname (str): hostname to be updated
        """
        try:
            old_hostname = self.get_hostname()

            is_valid_hostname(hostname)

            sh.hostname("-b", hostname)
            sh.echo(hostname, _out="/etc/hostname")

            try:
                # sed -i 's/ old$/ new/g' /etc/hosts
                sh.sed("-i", "s/ {}$/ {}/g".format(old_hostname, hostname),
                       "/etc/hosts")
            except:
                with open("/etc/hosts", "a") as f:
                    f.write("127.0.0.1       localhost {}\n".format(hostname))
            self.update(id=1, newObj={"hostname": hostname})
        except Exception as e:
            raise e
Ejemplo n.º 23
0
def dfs_dir_byplist(root_dir,markdown_file,level,logger=mylog.default_logger()):
    # generate the filelist, ignore the hidden files.

    effective_file=re.compile(r'(^.*_+|^[0-9]*_*)(.*)\.md$')
    plist_file_name=os.path.join(root_dir,'.Ulysses-Group.plist')
    print plist_file_name
    print root_dir, level
    filename_list,dirname_list=get_name_from_plist(plist_file_name)
    print filename_list
    alllists=filename_list+dirname_list
    efflists=[ filename for filename in filename_list if  effective_file.match(filename)]+dirname_list
    print efflists
    # efflists_title=[ effective_file.match(filename).group(2) for filename in alllists if  effective_file.match(filename)]


    #

    for filename in efflists:
        path = os.path.join(root_dir, filename)
        # print logger
        # logger.debug(filename+title)


        # write the file content according to level
        #TODO: 文件夹的处理,文件夹名+.md, .synopsis的处理
        if os.path.isdir(path):
            # markdown_file.write('#'*level+title)
            # markdown_file.write('\n\n')
            # if os.path.exists(str(path)+'/00.content'):
                # markdown_file.write(str(sh.cat(path+'/00.content'))+'\n')
            dfs_dir_byplist(path, markdown_file, level+1)
        else:
            # if title:
                # markdown_file.write('#'*level+title)
            # markdown_file.write('\n\n')
            # markdown_file.write(str(sh.sed('s/^#/'+'#'*level+'#/',path)))
            markdown_file.write(str(sh.sed('s/^#/'+'#'+'/',path)))
            markdown_file.write('\n\n')
Ejemplo n.º 24
0
def used_space():
    return int(sh.sed(sh.awk(sh.quota(), '{print $1}'), '-n', '4p')) * 1024
Ejemplo n.º 25
0
 def add(source_repo, f, apt_file):
     if not re.search(source_repo, f.read()):
         lgr.debug('Adding source repository {0}'.format(source_repo))
         sh.sed('-i', "2i {0}".format(source_repo), apt_file)
     else:
         lgr.debug('Repo {0} already added.'.format(source_repo))
Ejemplo n.º 26
0
Archivo: test.py Proyecto: ahhentz/sh
 def test_stdin_from_string(self):
     from sh import sed
     self.assertEqual(sed(_in="test", e="s/test/lol/").strip(), "lol")
Ejemplo n.º 27
0
 def remove_first_line(self):
     sh.sed('-i', '1d', self.path)
Ejemplo n.º 28
0
 def clean_proteins(self):
     print "Cleaning protein file of", self.name
     sh.sed("-i", 's/*$//', self.proteins)
Ejemplo n.º 29
0
#!/usr/bin/env python

import sys
import time
import getopt
import pexpect
from pexpect import pxssh
from sh import awk,sed,cat,tr,echo


# read and parse config file zz_full.info,
# generate alias_to_ip,intra_to_ip,number_dv dicts,
# and ip_list list:
# hostname alise list
alias = list(awk((sed(cat('zz_full.info'), "1d")), "{print $1}"))
alias = [ str(x.rstrip()) for x in alias ]
alias = filter(None, alias)
# Of course, you can merge the two above statements:
# alias = filter(None,  [ str(x.rstrip()) for x in alias ])
# or, the three above statements:
# alias = filter(None,  
#               [ str(x.rstrip()) for x in list(awk((sed(cat('zz_full.info'), "1d")), "{print $1}"))])
# intranet ip list
intra = list(awk((sed(cat('zz_full.info'), "1d")), "{print $6}"))
intra = [ str(x.rstrip()) for x in intra ]
intra = filter(None, intra)
# public ip list
ip_list = list(awk((sed(cat('zz_full.info'), "1d")), "{print $3}"))
ip_list = [ str(x.rstrip()) for x in ip_list ]
ip_list = filter(None, ip_list)
# deal with gameserver number
Ejemplo n.º 30
0
from sh import uname, sed, dpkg, awk, grep

# Get our current kernel version
# $(uname -r | sed -r 's/-[a-z]+//')

kernel_version = sed(uname('-r'), '-r', 's/-[a-z]+//').strip()

print('kernel version:', kernel_version)

# get & filter package list
packages = \
    grep(
        awk(
            dpkg('-l', 'linux-image-[0-9]*', 'linux-headers-[0-9]*', _env={'COLUMNS': '200'}),
            '/ii/{print $2}'
        ),
        '-ve',
        kernel_version
    )

print(packages.strip())
Ejemplo n.º 31
0
def dfs():
   # filename=glob.
    sh.sed('-i','s/^#/##/',filename)
Ejemplo n.º 32
0
def mmd2tex(markdown_file_name,main_title,type,lang):
    if not os.path.exists('latex'):
        sh.mkdir('latex')
    sh.cd('latex')
    if not os.path.exists('images') and os.path.exists('../images'):
        sh.ln('-s','../images','./')

    tex_file_name=main_title+'_'+type+'_'+lang+'.tex'

    # sh.pandoc(markdown_file_name,f="markdown_mmd",t="latex",o=tex_file_name)

    # generate proper tex file
    # main_title=str(sh.sed('-n','s/^# //p',markdown_file_name))
    tmp_markdown_file_name=tex_file_name.replace('.tex','.markdown')
    if type=='report':
        # report_markdown=main_title+'_report.markdown'
        sh.cp(markdown_file_name,tmp_markdown_file_name)
        # sh.sed('-i','-e','s/^#/'+'#/',tmp_markdown_file_name)

        sh.mmd2tex(tmp_markdown_file_name)
        # sh.mv(report_markdown,tex_file_name)
    elif type=='article':
        # article_markdown=main_title+'_article.markdown'
        sh.cp(markdown_file_name,tmp_markdown_file_name)
        sh.sed('-i','-e','s/^#/'+'#'*2+'/',tmp_markdown_file_name)
        sh.mmd2tex(tmp_markdown_file_name)
        # sh.mv(article_markdown.replace(,tex_file_name)
    else:
        return


    tex_file=open(tex_file_name,'r')
    content_list=tex_file.readlines()
    tex_file.close()
    if type=='report' and lang=='cn':
        prefix='''
% -*- coding: utf-8 -*-
\documentclass[UTF8,nofonts]{ctexrep}
\setCJKmainfont[BoldFont=STHeiti,ItalicFont=STKaiti]{STSong}
\setCJKsansfont[BoldFont=STHeiti]{STXihei}
\setCJKmonofont{STFangsong}

'''

    elif type=='article' and lang=='cn':
        prefix='''
% -*- coding: utf-8 -*-
\documentclass[UTF8,nofonts]{ctexart}
\setCJKmainfont[BoldFont=STHeiti,ItalicFont=STKaiti]{STSong}
\setCJKsansfont[BoldFont=STHeiti]{STXihei}
\setCJKmonofont{STFangsong}

'''

    elif type=='article' and lang=='en':
        prefix='''
% -*- coding: utf-8 -*-
\documentclass[UTF8]{article}

'''

    elif type=='report' and lang=='en':
        prefix='''
% -*- coding: utf-8 -*-
\documentclass[UTF8]{report}
'''

    secfix='''
\usepackage{graphicx}

\\begin{document}
\\title{%s} \\author{Haorui Lu}  \maketitle
\\tableofcontents
''' % (main_title)
    surfix='''
\end{document}
'''

    content_list.insert(0,secfix)
    content_list.insert(0,prefix)
    content_list.append(surfix)

    tex_file=open(tex_file_name,'w')
    tex_file.writelines(content_list)
    tex_file.close()
    _s=open(tex_file_name,'r').read().replace('includegraphics{','includegraphics[width=\\textwidth]{')
    open(tex_file_name,'w').write(_s)
    try:
        run_mytex=sh.Command("mytex.py")
        run_mytex(tex_file_name)
    except Exception, e:
        pass
Ejemplo n.º 33
0
 def replace_title(self, before, after):
     sh.sed('-i', '1s/%s/%s/' % (before, after), self.path)
Ejemplo n.º 34
0
def full_space():
    return int(sh.sed(sh.awk(sh.quota(), '{print $3}'), '-n', '4p')) * 1024