文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

python调用bash shell脚本方法

2024-04-02 19:55

关注

1. os.system()

help(os.system)

1.1. demo


>>> import os
>>> os.system("./test.sh")
hello python!
hello world!
256
>>> n>>8
1

2. os.popen()

help(os.system)

2.1 demo

os.popen(command):这种调用方式是通过管道的方式来实现,函数返回一个file对象,
里面的内容是脚本输出的内容(可简单理解为echo输出的内容),使用os.popen调用test.sh的情况


>> import os
>>> os.popen("./test.sh")
<open file './test.sh', mode 'r' at 0x7f6cbbbee4b0>
>>> f=os.popen("./test.sh")
>>> f
<open file './test.sh', mode 'r' at 0x7f6cbbbee540>
>>> f.readlines()
['hello python!\n', 'hello world!\n']

3. commands模块

4. subprocess

subprocess模块,允许创建很多子进程,创建的时候能指定子进程和子进程的输入、输出、错误输出管道,执行后能获取输出结果和执行状态。

说明:subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

args:表示shell指令,若以字符串形式给出shell指令,如"ls -l “则需要使shell = Ture。否则默认已数组形式表示shell变量,如"ls”,"-l"。
当使用比较复杂的shell语句时,可以先使用shlex模块的shlex.split()方法来帮助格式化命令,然后在传递给run()方法或Popen

4.1 demo


Stubs for subprocess

Based on http://docs.python.org/2/library/subprocess.html and Python 3 stub

from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text

_FILE = Union[None, int, IO[Any]]
_TXT = Union[bytes, Text]
_CMD = Union[_TXT, Sequence[_TXT]]
_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]]

# Same args as Popen.__init__
def call(args: _CMD,
     bufsize: int = ...,
     executable: _TXT = ...,
     stdin: _FILE = ...,
     stdout: _FILE = ...,
     stderr: _FILE = ...,
     preexec_fn: Callable[[], Any] = ...,
     close_fds: bool = ...,
     shell: bool = ...,
     cwd: _TXT = ...,
     env: _ENV = ...,
     universal_newlines: bool = ...,
     startupinfo: Any = ...,
     creationflags: int = ...) -> int: ...

def check_call(args: _CMD,
        bufsize: int = ...,
        executable: _TXT = ...,
        stdin: _FILE = ...,
        stdout: _FILE = ...,
        stderr: _FILE = ...,
        preexec_fn: Callable[[], Any] = ...,
        close_fds: bool = ...,
        shell: bool = ...,
        cwd: _TXT = ...,
        env: _ENV = ...,
        universal_newlines: bool = ...,
        startupinfo: Any = ...,
        creationflags: int = ...) -> int: ...

# Same args as Popen.__init__ except for stdout
def check_output(args: _CMD,
         bufsize: int = ...,
         executable: _TXT = ...,
         stdin: _FILE = ...,
         stderr: _FILE = ...,
         preexec_fn: Callable[[], Any] = ...,
         close_fds: bool = ...,
         shell: bool = ...,
         cwd: _TXT = ...,
         env: _ENV = ...,
         universal_newlines: bool = ...,
         startupinfo: Any = ...,
         creationflags: int = ...) -> bytes: ...

PIPE = ... # type: int
STDOUT = ... # type: int

class CalledProcessError(Exception):
  returncode = 0
  # morally: _CMD
  cmd = ... # type: Any
  # morally: Optional[bytes]
  output = ... # type: Any

  def __init__(self,
         returncode: int,
         cmd: _CMD,
         output: Optional[bytes] = ...) -> None: ...

class Popen:
  stdin = ... # type: Optional[IO[Any]]
  stdout = ... # type: Optional[IO[Any]]
  stderr = ... # type: Optional[IO[Any]]
  pid = 0
  returncode = 0

  def __init__(self,
         args: _CMD,
         bufsize: int = ...,
         executable: Optional[_TXT] = ...,
         stdin: Optional[_FILE] = ...,
         stdout: Optional[_FILE] = ...,
         stderr: Optional[_FILE] = ...,
         preexec_fn: Optional[Callable[[], Any]] = ...,
         close_fds: bool = ...,
         shell: bool = ...,
         cwd: Optional[_TXT] = ...,
         env: Optional[_ENV] = ...,
         universal_newlines: bool = ...,
         startupinfo: Optional[Any] = ...,
         creationflags: int = ...) -> None: ...

  def poll(self) -> int: ...
  def wait(self) -> int: ...
  # morally: -> Tuple[Optional[bytes], Optional[bytes]]
  def communicate(self, input: Optional[_TXT] = ...) -> Tuple[Any, Any]: ...
  def send_signal(self, signal: int) -> None: ...
  def terminate(self) -> None: ...
  def kill(self) -> None: ...
  def __enter__(self) -> 'Popen': ...
  def __exit__(self, type, value, traceback) -> bool: ...

# Windows-only: STARTUPINFO etc.

STD_INPUT_HANDLE = ... # type: Any
STD_OUTPUT_HANDLE = ... # type: Any
STD_ERROR_HANDLE = ... # type: Any
SW_HIDE = ... # type: Any
STARTF_USESTDHANDLES = ... # type: Any
STARTF_USESHOWWINDOW = ... # type: Any
CREATE_NEW_CONSOLE = ... # type: Any
CREATE_NEW_PROCESS_GROUP = ... # type: Any

到此这篇关于python调用bash shell脚本方法的文章就介绍到这了,更多相关python调用bash shell脚本内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯