2009-05-25 25 views
9

我使用/ bin/tcsh作爲我的默認shell。os.system()在哪個linux shell下執行命令?

但是,tcsh樣式命令os.system('setenv VAR val')不適用於我。但是os.system('export VAR = val')起作用。

所以我的問題是如何知道在哪個shell下的os.system()運行命令?

回答

5

os.system()只是調用system()系統調用(「man 3 system」)。在大多數* nixes這意味着你得到/bin/sh

請注意,export VAR=val在技術上不是標準語法(儘管bash瞭解它,我認爲ksh也是)。它不適用於/bin/sh實際上是Bourne shell的系統。在這些系統上,您需要導出並設置爲單獨的命令。 (這也適用於bash。)

9

這幾天你應該使用Subprocess模塊而不是os.system()。根據那裏的文檔,默認shell是/bin/sh。我相信os.system()的工作原理是一樣的。

編輯:我還應該提到,子流程模塊允許您通過env參數設置執行過程可用的環境。

+0

事實上,/ bin/sh(幾乎總是某種形式的Bourne shell)幾乎總是什麼意思,當任何* nix相關的說「shell」沒有限定。注意到如果你真的需要在特定的非Bourne shell下執行一些代碼段,你可以在這裏傳遞'/ path/to/tcsh -c'這個函數的'tcsh snippet'。 – 2009-05-25 06:33:36

2

如果你的命令是一個shell文件,並且該文件是可執行的,並且文件以「#!」開頭,那麼你可以選擇你的shell。

#!/bin/zsh 
Do Some Stuff 

你可以寫這個文件,然後用subprocess.Popen(filename,shell=True)執行它,你就可以使用任何你想要的外殼。

此外,請務必閱讀thisos.systemsubprocess.Popen

+0

我想指出的是,shell = True並不是必要的,但是後來它發生在我身上:它是否負責解釋shebang並據此採取行動? – 2010-02-13 18:41:36

+0

正確。 shell解釋「魔術」字節「#!」看看其他shell真的應該使用這個文件。 – 2010-02-13 18:52:47

10

剛剛讀取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 

希望這可以幫助別人,
乾杯!