如何从Python执行程序?操作系统。系统因路径上的空格而失败。

时间:2021-11-14 20:27:29

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

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

If I have the following script:

如果我有以下脚本:

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

Then it fails with the following error:

然后,它就会出现以下错误:

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

“C:\Temp\a”不能被识别为内部或外部命令、可操作程序或批处理文件。

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.

还要注意,将程序移动到非间隔路径也不是一个选项。


This does not work 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.

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

8 个解决方案

#1


252  

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.

子流程。调用将避免处理引用各种shell约定的问题。它接受一个列表,而不是一个字符串,因此参数更容易被分隔。即。

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

#2


58  

Here's a different way of doing it.

这是另一种方法。

If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.

如果您使用Windows,那么以下行为就像在浏览器中双击文件,或者将文件名作为DOS“start”命令的参数:该文件将以任何应用程序(如果有的话)与之关联的应用程序打开。

filepath = 'textfile.txt'
import os
os.startfile(filepath)

Example:

例子:

import os
os.startfile('textfile.txt')

This will open textfile.txt with Notepad if Notepad is associated with .txt files.

这将打开文本文件。如果Notepad与.txt文件相关联,则使用记事本。

#3


31  

The outermost quotes are consumed by Python itself, and the Windows shell doesn't see it. As mentioned above, Windows only understands double-quotes. Python will convert forward-slashed to backslashes on Windows, so you can use

最外层的引用被Python本身所消耗,而Windows shell则没有看到它。如上所述,Windows只理解双引号。Python将在Windows上将前向削减转换为反斜杠,因此您可以使用它。

os.system('"C://Temp/a b c/Notepad.exe"')

The ' is consumed by Python, which then passes "C://Temp/a b c/Notepad.exe" (as a Windows path, no double-backslashes needed) to CMD.EXE

“由Python使用,然后通过”C://Temp/a b C /Notepad。exe“(作为Windows路径,不需要双反斜杠)到CMD.EXE。

#4


15  

At least in Windows 7 and Python 3.1, os.system in Windows wants the command line double-quoted if there are spaces in path to the command. For example:

至少在Windows 7和Python 3.1中,操作系统。在Windows系统中,如果在命令路径中有空格,则需要对命令行进行双重引用。例如:

  TheCommand = '\"\"C:\\Temp\\a b c\\Notepad.exe\"\"'
  os.system(TheCommand)

A real-world example that was stumping me was cloning a drive in VirtualBox. The subprocess.call solution above didn't work because of some access rights issue, but when I double-quoted the command, os.system became happy:

一个真实的例子是在VirtualBox中克隆驱动器。子流程。上面的调用解决方案因为一些访问权限问题而没有工作,但是当我重复引用命令时,操作系统。系统变得快乐:

  TheCommand = '\"\"C:\\Program Files\\Sun\\VirtualBox\\VBoxManage.exe\" ' \
                 + ' clonehd \"' + OrigFile + '\" \"' + NewFile + '\"\"'
  os.system(TheCommand)

#5


7  

import win32api # if active state python is installed or install pywin32 package seperately

try: win32api.WinExec('NOTEPAD.exe') # Works seamlessly
except: pass

#6


4  

I suspect it's the same problem as when you use shortcuts in Windows... Try this:

我怀疑这和你在Windows中使用快捷方式的问题一样……试试这个:

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

#7


2  

For python >= 3.5 subprocess.run should be used in place of subprocess.call

对于python >= 3.5的子进程,应该使用“run”来代替子进程。

https://docs.python.org/3/library/subprocess.html#older-high-level-api

https://docs.python.org/3/library/subprocess.html older-high-level-api

import subprocess
subprocess.run(['notepad.exe', 'test.txt'])

#8


0  

Assume you want run your djnago web server (in linux), such as following code:

假设您希望运行您的djnago web服务器(在linux中),比如以下代码:

import subprocess

args = ['{}/manage.py'.format('/home/<you>/<path>'), 'runserver']
subprocess.Popen(args, stdout=subprocess.PIPE).poll()

If your path has a space, using such as following code:

如果您的路径有空格,请使用以下代码:

import subprocess

args = ['{}'.format('/home/<you>/<first path section> <second path section>')]
subprocess.Popen(args, stdout=subprocess.PIPE).poll()

Note: Do not forget accessing permission: chmod 777 -R <'yor path'>

注意:不要忘记访问权限:chmod 777 -R <'yor path'>。

#1


252  

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.

子流程。调用将避免处理引用各种shell约定的问题。它接受一个列表,而不是一个字符串,因此参数更容易被分隔。即。

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

#2


58  

Here's a different way of doing it.

这是另一种方法。

If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.

如果您使用Windows,那么以下行为就像在浏览器中双击文件,或者将文件名作为DOS“start”命令的参数:该文件将以任何应用程序(如果有的话)与之关联的应用程序打开。

filepath = 'textfile.txt'
import os
os.startfile(filepath)

Example:

例子:

import os
os.startfile('textfile.txt')

This will open textfile.txt with Notepad if Notepad is associated with .txt files.

这将打开文本文件。如果Notepad与.txt文件相关联,则使用记事本。

#3


31  

The outermost quotes are consumed by Python itself, and the Windows shell doesn't see it. As mentioned above, Windows only understands double-quotes. Python will convert forward-slashed to backslashes on Windows, so you can use

最外层的引用被Python本身所消耗,而Windows shell则没有看到它。如上所述,Windows只理解双引号。Python将在Windows上将前向削减转换为反斜杠,因此您可以使用它。

os.system('"C://Temp/a b c/Notepad.exe"')

The ' is consumed by Python, which then passes "C://Temp/a b c/Notepad.exe" (as a Windows path, no double-backslashes needed) to CMD.EXE

“由Python使用,然后通过”C://Temp/a b C /Notepad。exe“(作为Windows路径,不需要双反斜杠)到CMD.EXE。

#4


15  

At least in Windows 7 and Python 3.1, os.system in Windows wants the command line double-quoted if there are spaces in path to the command. For example:

至少在Windows 7和Python 3.1中,操作系统。在Windows系统中,如果在命令路径中有空格,则需要对命令行进行双重引用。例如:

  TheCommand = '\"\"C:\\Temp\\a b c\\Notepad.exe\"\"'
  os.system(TheCommand)

A real-world example that was stumping me was cloning a drive in VirtualBox. The subprocess.call solution above didn't work because of some access rights issue, but when I double-quoted the command, os.system became happy:

一个真实的例子是在VirtualBox中克隆驱动器。子流程。上面的调用解决方案因为一些访问权限问题而没有工作,但是当我重复引用命令时,操作系统。系统变得快乐:

  TheCommand = '\"\"C:\\Program Files\\Sun\\VirtualBox\\VBoxManage.exe\" ' \
                 + ' clonehd \"' + OrigFile + '\" \"' + NewFile + '\"\"'
  os.system(TheCommand)

#5


7  

import win32api # if active state python is installed or install pywin32 package seperately

try: win32api.WinExec('NOTEPAD.exe') # Works seamlessly
except: pass

#6


4  

I suspect it's the same problem as when you use shortcuts in Windows... Try this:

我怀疑这和你在Windows中使用快捷方式的问题一样……试试这个:

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

#7


2  

For python >= 3.5 subprocess.run should be used in place of subprocess.call

对于python >= 3.5的子进程,应该使用“run”来代替子进程。

https://docs.python.org/3/library/subprocess.html#older-high-level-api

https://docs.python.org/3/library/subprocess.html older-high-level-api

import subprocess
subprocess.run(['notepad.exe', 'test.txt'])

#8


0  

Assume you want run your djnago web server (in linux), such as following code:

假设您希望运行您的djnago web服务器(在linux中),比如以下代码:

import subprocess

args = ['{}/manage.py'.format('/home/<you>/<path>'), 'runserver']
subprocess.Popen(args, stdout=subprocess.PIPE).poll()

If your path has a space, using such as following code:

如果您的路径有空格,请使用以下代码:

import subprocess

args = ['{}'.format('/home/<you>/<first path section> <second path section>')]
subprocess.Popen(args, stdout=subprocess.PIPE).poll()

Note: Do not forget accessing permission: chmod 777 -R <'yor path'>

注意:不要忘记访问权限:chmod 777 -R <'yor path'>。