首页 > 编程知识 正文

jupternotebookshell命令执行python脚本,mysql执行sql脚本命令

时间:2023-05-06 15:20:53 阅读:235710 作者:3323

* git镇楼:git config --global core.filemode false*

实践出真知。虽然这个脚本代码量不大,但是也是经过3次修改才达到预期效果的。

* 第一次写的时候,凭逻辑认为代码是正确的,可以达到预期效果。但是拿到服务器上运行发现有问题* 第二次,在本地简单模拟了服务器的目录结构,测试通过了。但是拿到服务器运行,发现依然没有达到预期效果。* 第三次,为了让代码能正确执行,并达到预期效果。在代码中输出了当前执行路径,并在服务器上验证通过了。 如何利用python执行bash脚本?如何像cd xxx/一样任性跳转目录执行bash命令?

这两个问题解决了,才算是解决了使用python脚本执行bash命令的全部痛点。

一一解答:

如何利用python执行bash脚本?
os.popen(bash_comand)即可如何像cd xxx/一样任性跳转目录执行bash命令?
os.chdir(path)就如同cd xxx/一般,可以任性地切换到任意目录

于是,就有了如下代码 :

#!/usr/mmdqc/env python# -*- coding: utf-8 -*-# @name : find_t.py# @author : cat# @date : 2017/8/2.import osimport timedef bash_shell(bash_command): """ python 中执行 bash 命令 :param bash_command: :return: bash 命令执行后的控制台输出 """ try: return os.popen(bash_command).read().strip() except: return Nonedef find_target(target_path="./../", key='.git'): """ 查找目标目录所在的目录 : 如 /aa/bb/.git --> return /aa/bb/ :param target_path: :param key: target :return: """ walk = os.walk(target_path) for super_dir, dir_names, file_names in walk: for dir_name in dir_names: if dir_name == key: dir_full_path = os.path.join(super_dir, dir_name) # print(dir_full_path, super_dir, dir_name, sep=" ## ") yield super_dirif __name__ == '__main__': print("start execute bash ...........") st = time.time() cwd = os.getcwd() # this for repo for repo_path in find_target(os.getcwd(), key='.repo'): os.chdir(repo_path) if repo_path == os.getcwd(): print('find repo in -->', repo_path) print(bash_shell('pwd')) print(bash_shell('repo forall -c git config core.fileMode false --replace-all')) else: print('error in chdir 2 {}'.format(repo_path)) if os.getcwd() != cwd: os.chdir(cwd) if os.getcwd() != cwd: print('change 2 cwd FAIL !!! {}'.format(cwd)) # this for git for git_path in find_target(os.getcwd(), key='.git'): os.chdir(git_path) if git_path == os.getcwd(): print('find git in -->', git_path) print(bash_shell('pwd')) print(bash_shell('git config --global core.filemode false')) else: print('error in chdir 2 {}'.format(git_path)) if os.getcwd() != cwd: os.chdir(cwd) if os.getcwd() != cwd: print('change 2 cwd FAIL !!! {}'.format(cwd)) et = time.time() print('nn #### execute finished in {:.3f} seconds ####'.format(et - st)) print('n') # test for bash_command # print(bash_shell('git init')) # print(bash_shell('ls -al'))

于是,执行之后的输出如下:

bash_command = pwd/Users/cat/Desktop/testGit/a6bash_command = pwd/Users/cat/Desktop/testGit/a6/frameworks/basebash_command = pwd/Users/cat/Desktop/testGit/a6/packages/apps/Emailbash_command = pwd/Users/cat/Desktop/testGit/a6/packages/apps/Musicbash_command = pwd/Users/cat/Desktop/testGit/a6/packages/apps/Settingsbash_command = pwd/Users/cat/Desktop/testGit/a6/vender/customerspend time : 0.096 secondsend #################### endProcess finished with exit code 0

通过输出可以看到,所有的.repo以及.git目录所在目录是已经找出来了。然后执行bash_commad(command)即可在仓库目录执行git / repo命令了。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。