有没有办法在Windows上的python中运行命令?

时间:2016-06-28 17:11:32

标签: python

我正在尝试使用Windows中的python执行如下命令并运行 WindowsError: [Error 2] The system cannot find the file specified错误,目前我的PC上没有script.exe,手动运行它会抛出错误'script.exe' is not recognized as an internal or external command,operable program or batch file.,我希望通过python运行同样的错误,如何修复这个错误?非常感谢任何输入

代码: -

cmd = "script.exe"
print "Executing " + cmd
fetchPipe = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, error) = fetchPipe.communicate()

2 个答案:

答案 0 :(得分:2)

您必须在以下解决方案之一中进行选择:

  1. 传递relative path并在尝试打开文件之前使用os.chdir('folderPath')将当前工作目录设置为包含script.exe的同一文件夹
  2. OR

    1. 使用absolute path
    2. script.exe传递到cmd = os.getcwd() + "\\script.exe"文件

      使用第二种方法,您将拥有:

      cmd = os.getcwd() + "\\script.exe"
      print "Executing " + cmd
      fetchPipe = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      (output, error) = fetchPipe.communicate()
      

答案 1 :(得分:1)

def find_abs_path(executable_fname):
    if os.path.exists(executable_fname): # in case it is in our cwd
        return os.path.abspath(os.path.join(".",executable_fname))
    for dirname in os.environ["PATH"].split(";"): # split dependant on your os
        if executable_fname in os.listdir(dirname):
           return os.path.join(dirname,executable_fname)

应搜索您的路径并找到可执行文件的绝对路径

这是推荐的做法......

... 然而你可以传入一个env

subprocess.Popen(cmd_args,env=os.environ,...)

这应该为运行的子shell提供相同的PATH变量......因此它可能会找到可执行文件......