【问题标题】:os.system() execute command under which linux shell?os.system() 在哪个linux shell下执行命令?
【发布时间】:2009-05-25 03:30:14
【问题描述】:

我使用/bin/tcsh 作为我的默认外壳。

但是,tcsh 样式命令os.system('setenv VAR val') 对我不起作用。但是os.system('export VAR=val') 有效。

所以我的问题是如何知道os.system()在哪个shell下运行命令?

【问题讨论】:

    标签: python linux shell


    【解决方案1】:

    刚刚阅读Executing BASH from Python,然后是17.1. subprocess — Subprocess management — Python v2.7.3 documentation,我看到了executable 参数;它似乎有效:

    $ python
    Python 2.7.1+ (r271:86832, Sep 27 2012, 21:16:52) 
    [GCC 4.5.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> print os.popen("echo $0").read()
    sh
    >>> import subprocess
    >>> print subprocess.call("echo $0", shell=True).read()
    /bin/sh
    >>> print subprocess.Popen("echo $0", stdout=subprocess.PIPE, shell=True).stdout.read()
    /bin/sh
    >>> print subprocess.Popen("echo $0", stdout=subprocess.PIPE, shell=True, executable="/bin/bash").stdout.read()
    /bin/bash
    >>> print subprocess.Popen("cat <(echo TEST)", stdout=subprocess.PIPE, shell=True).stdout.read()
    /bin/sh: Syntax error: "(" unexpected
    >>> print subprocess.Popen("cat <(echo TEST)", stdout=subprocess.PIPE, shell=True, executable="/bin/bash").stdout.read()
    TEST
    

    希望这对某人有所帮助,
    干杯!

    【讨论】:

    • 我就是这样的人。这就是我一直在寻找的。感谢您注意到这一点:)
    • 是的,当使用 tee 将标准输出从单个命令传送到多个命令时,情况就是如此,例如 command out=stdout | tee &gt;(command_1 in=stdin) &gt;(command_2 in=stdin)。感谢发帖,点个赞~
    【解决方案2】:

    这些天你应该使用Subprocess 模块而不是os.system()。根据那里的文档,默认外壳是/bin/sh。我相信os.system() 的工作方式是一样的。

    编辑:我还要提一下,子进程模块允许您通过env 参数设置执行进程可用的环境。

    【讨论】:

    • 确实,/bin/sh(几乎总是某种形式的 bourne shell)几乎总是当任何与 *nix 相关的东西无条件地说“shell”时的意思。还需要注意的是,如果您确实需要在特定的非 bourne shell 下执行一些 sn-p,您可以传递类似 '/path/to/tcsh -c "your tcsh sn-p here" 之类的函数'。
    【解决方案3】:

    os.system() 只是调用system() 系统调用(“man 3 system”)。在大多数 *nixes 中,这意味着你会得到/bin/sh

    请注意,export VAR=val 在技术上不是标准语法(尽管bash 可以理解,我认为ksh 也可以)。它不适用于/bin/sh 实际上是 Bourne shell 的系统。在这些系统上,您需要导出并设置为单独的命令。 (这也适用于bash。)

    【讨论】:

      【解决方案4】:

      如果你的命令是一个 shell 文件,并且文件是可执行的,并且文件以“#!”开头,你可以选择你的 shell。

      #!/bin/zsh
      Do Some Stuff
      

      你可以编写这个文件,然后用subprocess.Popen(filename,shell=True) 执行它,你就可以使用任何你想要的shell。

      另外,请务必阅读this 关于os.systemsubprocess.Popen

      【讨论】:

      • 我打算指出 shell=True 不是必需的,但后来我想到:是负责解释 shebangs 并采取相应行动的 shell?
      • 正确。外壳解释“魔术”字节“#!”看看其他 shell 应该真正使用这个文件。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 2017-05-27
      • 2022-09-23
      • 1970-01-01
      相关资源
      最近更新 更多