如何在Python中调用自定义命令行函数
我试图用python调用一个自定义的命令行函数。我在如何在Python中调用自定义命令行函数,python,bash,command-line,os.system,Python,Bash,Command Line,Os.system,我试图用python调用一个自定义的命令行函数。我在/.bash_profile中使用apple脚本定义了我的函数,如下所示: function vpn-connect { /usr/bin/env osascript <<-EOF tell application "System Events" tell current location of network preferences set VPN to service "YESV
/.bash_profile
中使用apple脚本定义了我的函数,如下所示:
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
}
我使用python vpn.py
运行它,得到了以下输出:
vpn Choushishi$ python vpn.py
It is running.
sh: vpn-connect: command not found
这证明了调用自定义函数与调用系统预定义的函数在某种程度上是不同的。我查看了pydoc操作系统
,但找不到有用的信息
vpn=subprocess.Popen(["bash"],shell=True,stdin= subprocess.PIPE)
vpn.communicate("source /Users/YOUR_USER_NAME/.bash_profile;vpn-connect")
os.system('bash -c "source /Users/YOUR_USER_NAME/.bash_profile;vpn-connect"')
import subprocess
subprocess.call(['vpn-connect'], shell = True)
import os
os.system('bash -c vpn-connect')
据我怀疑这与以下事实有关:
os.system
启动子shell,并且对于非登录shell不读取.bash_配置文件,但我不知道为什么现有函数在子shell中不可见。您可能希望查看,而不是使用shell脚本作为中介。os.system('bash-c“source/Users/YOUR_USER\u NAME/.bash\u profile;vpn connect””)
有效。谢谢!另一个选项是使用vpn=subprocess.Popen([“bash”],shell=True,stdin=subprocess.PIPE);vpn.communicate(“vpn connect”);
import os
os.system('bash -c vpn-connect')