如何从 Python 执行程序? os.system 由于路径中存在空格而失败

发布于 2024-07-07 20:51:31 字数 863 浏览 8 评论 0原文

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

如果我有以下脚本:

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

那么它会失败并出现以下错误:

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

如果我用引号转义程序:

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

那么它就可以工作。 但是,如果我添加一个参数,它会再次停止工作:

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

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

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


这也不起作用:

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

注意交换的单/双引号。

无论这里有或没有记事本参数,它都会失败并显示错误消息

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

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

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

记忆之渊 2024-07-14 20:51:31

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

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

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'])
风吹雪碎 2024-07-14 20:51:31

这是一种不同的方法。

如果您使用的是 Windows,则以下操作类似于在资源管理器中双击文件,或将文件名作为 DOS“启动”命令的参数:使用与其扩展名关联的任何应用程序(如果有)打开该文件。

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

示例:

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

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

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.

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.

善良天后 2024-07-14 20:51:31

最外面的引号由 Python 本身使用,Windows shell 看不到它。 如上所述,Windows 只理解双引号。
Python 将在 Windows 上将正斜杠转换为反斜杠,因此您可以使用

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

' 由 Python 使用,然后传递“C://Temp/abc/Notepad.exe”(作为 Windows 路径,不需要双反斜杠)到CMD.EXE

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

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

笑看君怀她人 2024-07-14 20:51:31

至少在 Windows 7 和 Python 3.1 中,如果命令路径中有空格,Windows 中的 os.system 需要命令行用双引号引起来。 例如:

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

一个令我困惑的现实例子是在 VirtualBox 中克隆驱动器。 由于某些访问权限问题,上面的 subprocess.call 解决方案不起作用,但是当我双引号该命令时,os.system 变得很高兴:

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

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:

  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:

  TheCommand = '\"\"C:\\Program Files\\Sun\\VirtualBox\\VBoxManage.exe\" ' \
                 + ' clonehd \"' + OrigFile + '\" \"' + NewFile + '\"\"'
  os.system(TheCommand)
懒的傷心 2024-07-14 20:51:31

对于 python >= 3.5 应使用 subprocess.run 代替 subprocess.call

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

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

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

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

import subprocess
subprocess.run(['notepad.exe', 'test.txt'])
傲影 2024-07-14 20:51:31
import win32api # if active state python is installed or install pywin32 package seperately

try: win32api.WinExec('NOTEPAD.exe') # Works seamlessly
except: pass
import win32api # if active state python is installed or install pywin32 package seperately

try: win32api.WinExec('NOTEPAD.exe') # Works seamlessly
except: pass
笑忘罢 2024-07-14 20:51:31

我怀疑这与您在 Windows 中使用快捷方式时遇到的问题相同...尝试以下操作:

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

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

import os
os.system("\"C:\\Temp\\a b c\\Notepad.exe\" C:\\test.txt")
狼性发作 2024-07-14 20:51:31

对于 Python 3.7,请使用 subprocess.call 。 使用原始字符串来简化 Windows 路径:

import subprocess
subprocess.call([r'C:\Temp\Example\Notepad.exe', 'C:\test.txt'])

For Python 3.7, use subprocess.call. Use raw string to simplify the Windows paths:

import subprocess
subprocess.call([r'C:\Temp\Example\Notepad.exe', 'C:\test.txt'])
贵在坚持 2024-07-14 20:51:31

假设我们要运行 Django Web 服务器(在 Linux 中),路径之间有空格 (path='/home//;'),因此请执行以下操作:

import subprocess

args = ['{}/manage.py'.format('/home/<you>/<first-path-section> <second-path-section>'), 'runserver']
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()

if not error_:
    print(output)
else:
    print(error_)

[注意]:

  • 不要忘记访问权限:chmod 755 -R <'您的路径'>
  • < code>manage.py 可执行:chmod +x manage.py

Suppose we want to run your Django web server (in Linux) that there is space between your path (path='/home/<you>/<first-path-section> <second-path-section>'), so do the following:

import subprocess

args = ['{}/manage.py'.format('/home/<you>/<first-path-section> <second-path-section>'), 'runserver']
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()

if not error_:
    print(output)
else:
    print(error_)

[Note]:

  • Do not forget accessing permission: chmod 755 -R <'yor path'>
  • manage.py is exceutable: chmod +x manage.py
何时共饮酒 2024-07-14 20:51:31

不需要子进程,可以简单地实现

GitPath="C:\\Program Files\\Git\\git-bash.exe"# Application File Path in mycase its GITBASH
os.startfile(GitPath)

No need for sub-process, It can be simply achieved by

GitPath="C:\\Program Files\\Git\\git-bash.exe"# Application File Path in mycase its GITBASH
os.startfile(GitPath)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文