如何在Python中调用自定义命令行函数

1 投票
1 回答
637 浏览
提问于 2025-04-18 04: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,但没有找到有用的信息。

1 个回答

3
  1. 一种方法是在之前读取 ./bash_profile 文件。正如 @anishsane 指出的,你可以这样做:

    vpn=subprocess.Popen(["bash"],shell=True,stdin= subprocess.PIPE)
    vpn.communicate("source /Users/YOUR_USER_NAME/.bash_profile;vpn-connect")
    
  2. 或者使用 os.system 命令

    os.system('bash -c "source /Users/YOUR_USER_NAME/.bash_profile;vpn-connect"')
    
  3. 或者试试这个

    import subprocess
    subprocess.call(['vpn-connect'], shell = True)
    
  4. 再试试这个

    import os
    os.system('bash -c vpn-connect')
    

    具体可以参考 http://linux.die.net/man/1/bash

撰写回答