从用户获取输入,然后使用子流程启动流程

问题描述 投票:1回答:1

我想有一个程序,它接受用户的输入,然后尝试打开该文件/程序。我可以使用subprocess.call([file])执行此操作,但这仅适用于基本程序,如记事本。如果有任何参数,我也希望能够将agruments传递给程序。如:

简单的程序(我已经实现/尝试过)

import subprocess
file = input()
subprocess.call([file])

复杂的程序(试过这段代码,但由于没有找到这样的文件而给出错误)

import subprocess
file = input("File Name: ") #File = qemu-system-x86_64 -boot order=d F:/arch
subprocess.call([file]) # Tries to start qemu with -boot order=d F:/arch args

所以我试着为此寻找答案,但我学会了将所有参数传递给程序,你就像这样([file,args])。所以在第二个例子,当我尝试运行带参数的程序时,我得到一个没有找到文件的错误。另外我不能使用os模块,特别是os.system()因为我无法访问cmd

python python-3.x subprocess
1个回答
1
投票

在Windows上,您可以使用单个字符串版本作为第一个参数:

subprocess.call(file)

因为底层系统调用使用完整的命令行。在Posix系统上,您必须使用正确拆分的列表。 shlex模块是一个方便的方式:

import subprocess
import shlex
file = input("File Name: ") #File = qemu-system-x86_64 -boot order=d F:/arch
subprocess.call(shlex.split(file))
© www.soinside.com 2019 - 2024. All rights reserved.