如何从python执行程序?操作系统失败 [英] How do I execute a program from python? os.system fails

查看:56
本文介绍了如何从python执行程序?操作系统失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to run a command with os.system but i get an error

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

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

It will work if I only run:

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

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

Or if I have no space in the python path like this

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

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

But if I have two pairs of double-quotes in the command both in python path and in txt path I get an error...

推荐答案

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

os.system has some serious drawbacks, especially with space in filenames and w.r.t. security. I suggest you look into the subprocess module and particularly subprocess.check_call, which is much more powerful. You could then do e.g.

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

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

Of course, make sure to take great care not to have user-determined variables in these calls unless the user is already running the script herself from the command line with the same privileges.

这篇关于如何从python执行程序?操作系统失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆