【问题标题】:How do I execute a program from python? os.system fails如何从 python 执行程序?操作系统失败
【发布时间】:2015-02-24 02:02:21
【问题描述】:

我想用 os.system 运行命令,但出现错误

c:/fe ' is not recognized as an internal or external command, operable program or batch file

我使用的代码是

import os
os.system('"C:\\fe re\\python.exe" program "c:\\test now\\test.txt" http://site.to.explore')

如果我只运行它就会起作用:

import os
os.system('"C:\\fe re\\python.exe" program -h')

或者如果我在 python 路径中没有这样的空间

import os
os.system('C:\\fere\\python.exe program "c:\\test now\\test.txt" http://site.to.explore')

但是如果我在 python 路径和 txt 路径中的命令中都有两对双引号,我会收到一个错误...

【问题讨论】:

  • 这有什么帮助吗:stackoverflow.com/questions/1912818/…?
  • 怎么样:os.system('""C:\\fe re\\python.exe" program "c:\\test now\\test.txt" http://site.to.explore"')?
  • 啊……太好了……谢谢……

标签: python windows python-2.7 os.system


【解决方案1】:

os.system 有一些严重的缺点,尤其是文件名中的空格和 w.r.t.安全。我建议您查看subprocess 模块,尤其是subprocess.check_call,它更强大。然后你可以做例如

import subprocess
subprocess.check_call(["c:\\fe re\\python.exe", "program", etcetc...])

当然,请务必注意不要在这些调用中包含用户确定的变量,除非用户已经以相同的权限从命令行自己运行脚本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-30
    • 2010-10-17
    • 2022-08-18
    • 2016-11-28
    • 2021-01-14
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    相关资源
    最近更新 更多