在python中运行程序提示符

2024-09-27 23:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何在python中使用命令提示符。问题是,我需要运行一个基于python的程序,我以前是在命令提示符下运行的。但是,我需要多次运行这个程序,因此,我想自动化它。程序需要与特定文件夹中的文件一起运行,并且它使用位于同一特定文件夹中的配置文件。最后,我还需要它在完成每个过程后提供一个日志文件。我以前都是在命令提示符下完成这一切的:

C:\Users\Gabriel\Documents\vina_tutorial>"\Program Files (x86)\The Scripps Research Institute\Vina\vina.exe" --config conf.txt --log log.txt

我试过使用python:

import subprocess
subprocess.Popen('C:\\Program Files (x86)\\The Scripps Research Institute\\Vina\\vina.exe -config ' + 'conf.txt', cwd='C:\\Users\\Gabriel\\Documents\\vina_tutorial')

然而,它似乎不起作用。(在第一步中,我省略了日志文件)

关于如何继续或在哪里我可以学到一些关于它的提示?你知道吗


Tags: 文件the程序txt文件夹filesprogramusers
1条回答
网友
1楼 · 发布于 2024-09-27 23:21:03

您需要将shell命令拆分为传递给Popen的独立参数。Read the documentation

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

此外,您可能需要在Windows文件路径中转义反斜杠。您可能还需要将引号括起来,即'"C:\\Program Files (x86)\\etc..\\foo.exe"'

相关问题 更多 >

    热门问题