【问题标题】:how to run an exe file with the arguments using python如何使用python运行带有参数的exe文件
【发布时间】:2013-04-02 11:28:03
【问题描述】:

假设我有一个文件RegressionSystem.exe。我想用-config 参数执行这个可执行文件。命令行应该是这样的:

RegressionSystem.exe -config filename

我试过这样:

regression_exe_path = os.path.join(get_path_for_regression,'Debug','RegressionSystem.exe')
config = os.path.join(get_path_for_regression,'config.ini')
subprocess.Popen(args=[regression_exe_path,'-config', config])

但是没有用。

【问题讨论】:

  • 怎么没用?错误信息是什么?

标签: python windows python-2.7 subprocess


【解决方案1】:

如果需要,您也可以使用subprocess.call()。例如,

import subprocess
FNULL = open(os.devnull, 'w')    #use this if you want to suppress output to stdout from the subprocess
filename = "my_file.dat"
args = "RegressionSystem.exe -config " + filename
subprocess.call(args, stdout=FNULL, stderr=FNULL, shell=False)

callPopen 之间的区别基本上是call 是阻塞的,而Popen 不是,Popen 提供更通用的功能。通常call 适用于大多数用途,它本质上是Popen 的一种方便形式。你可以在this question阅读更多内容。

【讨论】:

    【解决方案2】:

    对于其他发现此问题的人,您现在可以使用subprocess.run()。这是一个例子:

    import subprocess
    subprocess.run(["RegressionSystem.exe", "-config filename"])
    

    参数也可以作为字符串发送,但您需要设置shell=True。官方文档可以在here找到。

    【讨论】:

      【解决方案3】:
      os.system("/path/to/exe/RegressionSystem.exe -config "+str(config)+" filename")
      

      应该可以。

      【讨论】:

      • os.system 似乎被阻止。也就是说,直到 exe 运行完成才返回。这是该提议解决方案的一个值得注意的特征/限制。
      【解决方案4】:

      在这里,我想提供一个很好的例子。在下面,我得到了当前程序的参数count,然后将它们附加到一个数组中作为argProgram = []。最后我打电话给subprocess.call(argProgram) 完全直接地传递它们:

      import subprocess
      import sys
      
      argProgram = []
      
      if __name__ == "__main__":
      
          # Get arguments from input
          argCount = len(sys.argv)
          
          # Parse arguments
          for i in range(1, argCount):
              argProgram.append(sys.argv[i])
      
          # Finally run the prepared command
          subprocess.call(argProgram)
      

      在这个code 中,我应该运行一个名为“Bit7z.exe”的可执行应用程序:

      python Bit7zt.py Bit7zt.exe -e 1.zip -o extract_folder
      

      注意: 我使用了for i in range(1, argCount): 语句,因为我不需要第一个参数。

      【讨论】:

        【解决方案5】:

        我不明白参数是如何工作的。 例如:“-fps 30”不是一个,而是两个必须像这样传递的参数(Py3)

        args=[exe,"-fps","30"].
        

        也许这对某人有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-27
          • 2015-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-21
          • 1970-01-01
          • 2015-05-18
          相关资源
          最近更新 更多