【发布时间】:2014-06-11 00:53:13
【问题描述】:
我正在尝试在 python 中调用自定义的命令行函数。我在/.bash_profile 中使用苹果脚本定义了我的函数,如下所示:
function vpn-connect {
/usr/bin/env osascript <<-EOF
tell application "System Events"
tell current location of network preferences
set VPN to service "YESVPN" -- your VPN name here
if exists VPN then connect VPN
repeat while (current configuration of VPN is not connected)
delay 1
end repeat
end tell
end tell
EOF
}
当我在bash 中测试$ vpn-connect 时,vpn-connect 工作正常。我的 vpn 连接很好。
所以我创建了vpn.py,其中包含以下代码:
import os
os.system("echo 'It is running.'")
os.system("vpn-connect")
我用python vpn.py 运行它并得到以下输出:
vpn Choushishi$ python vpn.py
It is running.
sh: vpn-connect: command not found
这证明调用自定义函数与调用系统预定义的函数在某种程度上是不同的。我查看了pydoc os,但找不到有用的信息。
【问题讨论】:
-
我怀疑这与
os.system启动一个子shell,并且 .bash_profile 不读取非登录shell的事实有关,但我不知道为什么现有功能不会在子shell中可见。 -
您可能想查看interfacing with AppleScript directly from Python,而不是使用 shell 脚本作为中介。
标签: python bash command-line os.system