In python 2.4, how can I execute external commands with csh instead of bash?

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

Without using the new 2.6 subprocess module, how can I get either os.popen or os.system to execute my commands using the tcsh instead of bash? I need to source some scripts which are written in tcsh before executing some other commands and I need to do this within python2.4.

EDIT Thanks for answers using 'tcsh -c', but I'd like to avoid this because I have to do escape madness. The string will be interpreted by bash and then interpreted by tcsh. I'll have to do something like:

os.system("tcsh -c '"+re.compile("'").sub(r"""'"'"'""",my_cmd)+"'") 

Can't I just tell python to open up a 'tcsh' sub-process instead of a 'bash' subprocess? Is that possible?

P.S. I realize that bash is the cat's meow, but I'm working in a corporate environment and I'm going to choose to not fight a tcsh vs bash battle -- bigger fish to fry.

回答1:

os.system() calls system(3) directly, and this system call is the one that "chooses" the shell. I put that in quotes, because system(3) will always execute /bin/sh.

Thus, if you want Python to use a different shell, you have several options:

  • Change the symlink /bin/sh to point to tcsh. This will have an effect on the whole system, which shouldn't be a problem since scripts that need bash features should start with /bin/bash anyway.

  • Run your Python script from a chroot environment where /bin/sh points to tcsh.

  • Replace /bin/sh with a script that executes bash or tcsh depending on who calls it (you could, for example, pass an additional environment variable.)

  • Put everything you want to execute in tcsh in a separate shell script and call that with os.system('tcsh -c...'). This way you don't have to escape anything.



回答2:

Just prefix the shell as part of your command. I don't have tcsh installed but with zsh:

>>> os.system ("zsh -c 'echo $0'") zsh 0 


回答3:

How about:

>>> os.system("tcsh your_own_script") 

Or just write the script and add

#!/bin/tcsh 

at the beginning of the file and let the OS take care of that.



回答4:

Just set the shell to use to be tcsh:

>>> os.environ['SHELL'] = 'tcsh' >>> os.environ['SHELL'] 'tcsh' >>> os.system("echo $SHELL") tcsh 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!