3 回答

TA貢獻1821條經驗 獲得超5個贊
您需要export該功能(帶有-f選項):
$ function func()
> {
> echo "Custom env : $CUSTOM_ENV"
> }
$ export -f func
$ export CUSTOM_ENV="abc"
$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system('func')
Custom env : abc
0
請注意,exporting 函數(和變量)會將函數和變量的副本導出到它們從中導出的 shell 的子進程。它們在父(或兄弟)進程中不可用。此外,在子流程中更改它們不會影響原始副本。
此外,導出函數是僅用于 bash 的事情,因此這僅在父 shell 和從 python 啟動的 shell 都是 bash 時才有效。在 bash 不是默認值的操作系統上(例如最近發布的 Ubuntu 和 Debian),您需要明確運行 bash,否則它將無法運行。這一切使它變得相當脆弱,正如@triplee 指出的那樣,這不是一個好主意。
添加回答
舉報