Python, subprocess, call(), check_call and returncode to find if a command exists

后端 未结 3 2099
执笔经年
执笔经年 2021-02-07 04:35

I\'ve figured out how to use call() to get my python script to run a command:

import subprocess

mycommandline = [\'lumberjack\', \'-sleep all night\', \'-work a         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-07 05:15

    Wow, that was fast! I combined Theodros Zelleke's simple example and steveha's use of functions with abarnert comment about OSError and Lattyware's comment about moving files:

    import os, sys, subprocess
    
    def nameandpath():
        try:
            subprocess.call([os.getcwd() + '/lumberjack']) 
            # change the word lumberjack on the line above to get an error
        except OSError:
            print('\nCould not find lumberjack, please reinstall.\n')
            # if you're using python 2.x, change the () to spaces on the line above
    
    try:
        subprocess.call(['lumberjack'])
        # change the word lumberjack on the line above to get an error
    except OSError:
        nameandpath()
    

    I tested it on Mac OS-X (6.8/Snow Leopard), Debian (Squeeze) and Windows (7). It seemed to work the way I wanted it to on all three operating systems. I tried using check_call and CalledProcessError but no matter what I did, I seemed to get an error every time and I couldn't get the script to handle the errors. To test the script I changed the name from 'lumberjack' to 'deadparrot', since I had lumberjack in the directory with my script.

    Do you see any problems with this script the way it's written?

提交回复
热议问题