如何从 Python 执行程序?os.system 由于路径中的空格而失败 [英] How do I execute a program from Python? os.system fails due to spaces in path

查看:160
本文介绍了如何从 Python 执行程序?os.system 由于路径中的空格而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要执行外部程序的 Python 脚本,但由于某种原因失败了.

I have a Python script that needs to execute an external program, but for some reason fails.

如果我有以下脚本:

import os;
os.system("C:\\Temp\\a b c\\Notepad.exe");
raw_input();

然后它失败并出现以下错误:

Then it fails with the following error:

'C:\Temp\a' 不是内部或外部命令,也不是可运行的程序或批处理文件.

'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.

如果我用引号转义程序:

If I escape the program with quotes:

import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe"');
raw_input();

然后就可以了.但是,如果我添加一个参数,它会再次停止工作:

Then it works. However, if I add a parameter, it stops working again:

import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"');
raw_input();

执行程序并等待它完成的正确方法是什么?我不需要从中读取输出,因为它是一个执行工作然后退出的可视化程序,但我需要等待它完成.

What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.

另请注意,将程序移动到非间隔路径也不是一种选择.

Also note, moving the program to a non-spaced path is not an option either.

这也不起作用:

import os;
os.system("'C:\\Temp\\a b c\\Notepad.exe'");
raw_input();

注意交换的单/双引号.

Note the swapped single/double quotes.

这里有或没有记事本的参数,它会失败并显示错误信息

With or without a parameter to Notepad here, it fails with the error message

文件名、目录名或卷标语法不正确.

The filename, directory name, or volume label syntax is incorrect.

推荐答案

subprocess.call 将避免必须处理各种 shell 的引用约定的问题.它接受一个列表,而不是一个字符串,所以参数更容易分隔.即

subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.

import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])

这篇关于如何从 Python 执行程序?os.system 由于路径中的空格而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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