V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
meteor2013
V2EX  ›  Python

请问怎样用 Python 去执行 sh 文件比较好呢??

  •  
  •   meteor2013 · 2016-05-24 14:49:26 +08:00 · 3542 次点击
    这是一个创建于 2894 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如有个 sh 文件 test.sh , 运行每次只能输入一个句子:
    $ echo 'this is the first sentence' | test.sh


    如果有 100 个句子,我想用 Python 去循环运行这个 test.sh ,应该在 Python 里面怎样执行 sh 文件呢?
    9 条回复    2016-05-31 13:15:46 +08:00
    xiaket
        1
    xiaket  
       2016-05-24 15:35:51 +08:00 via iPhone
    循环调 sh 这个库
    meteor2013
        2
    meteor2013  
    OP
       2016-05-24 15:39:05 +08:00 via iPhone
    @xiaket 能说具体点吗
    dphdjy
        3
    dphdjy  
       2016-05-24 15:42:27 +08:00 via Android
    keyword: Python shell subprocess
    congeec
        4
    congeec  
       2016-05-24 15:50:43 +08:00
    其实用 shell 最简单
    python 里面 os.system 也简单粗暴
    ``` Python
    for i in sentences:
    os.system('echo ' + i + ' | test.sh')
    ```
    aristotll
        5
    aristotll  
       2016-05-24 20:44:33 +08:00
    @congeec os.system 不推荐用了吧
    congeec
        6
    congeec  
       2016-05-24 21:26:57 +08:00
    @aristotll 自己用的一次性脚本,又没啥安全问题
    quxw
        7
    quxw  
       2016-05-24 22:46:26 +08:00
    ipython

    !source test.sh
    playniuniu
        8
    playniuniu  
       2016-05-25 08:55:02 +08:00   ❤️ 1
    python 有个第三方库就叫做 sh , pip install sh 自己看看官方文档,非常方便
    sleshep
        9
    sleshep  
       2016-05-31 13:15:46 +08:00
    popen
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2943 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 14:15 · PVG 22:15 · LAX 07:15 · JFK 10:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.