Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中调用自定义命令行函数_Python_Bash_Command Line_Os.system - Fatal编程技术网

如何在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

我试图用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 "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操作系统
,但找不到有用的信息

  • 一种方法是在之前阅读./bash_概要文件。正如@anishsane所指出的,你可以这样做:

    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')