实际从Python脚本执行程序

问题描述 投票:0回答:2

我已经搞砸这个问题一个多小时了,我在 Stack Overflow 上查看了几个问题。我正在尝试实际执行一个程序,而不是用 python python 进程包装它来输出。

我有一个代码来监视守护进程,如果出于某种原因它关闭了,我想重新打开它。我发现唯一能做到这一点的是 os.startfile。我的问题是我无法向 os.startfile 添加任何命令行参数。

我已经阅读了 os.startfile 上的 docs,但我很难理解它。在文档中,它讨论的是开放启动参数等,但在 PyCharm 的代码示例中,它仅显示函数、路径和操作的两个参数

还有这个...

from sys import argv
from os import startfile

if len(argv) == 1:
    startfile(r'C:\Windows\System32\cmd.exe /k python.exe os_startfile.py process', operation = 'open')
else:
    for index, enum in enumerate(argv):
        print(index, enum)
exit()

正在生成错误...

Traceback (most recent call last):
  File "C:\Users\phpjunkie\Python\Scripts\testing\os_startfile.py", line 5, in <module>
    startfile(r'C:\Windows\System32\cmd.exe /k python.exe os_startfile.py process', operation = 'open')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Windows\\System32\\cmd.exe /k python.exe os_startfile.py process'
python operating-system subprocess
2个回答
0
投票

根据 docs.python.org/3.11/library/os.html#os.startfile 的文档,它显示的争论比 PyCharm 在其文档弹出窗口中显示的内容更多。我可以使用以下代码来实现它

from sys import argv
from os import startfile

if len(argv) == 1:
    startfile(filepath = r'C:\Windows\System32\cmd.exe ', operation = 'open', arguments = '/k python.exe os_startfile.py process')
else:
    for index, enum in enumerate(argv):
        print(index, enum)
exit()

PyCharm 将

filepath
arguments
显示为
Unexpected argument
警告。 PyCharm 也在报告
Parameter "path" unfilled


0
投票

虽然@phpjunkie的答案解决了你的问题,但你应该看看 subprocess.run

© www.soinside.com 2019 - 2024. All rights reserved.