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

2024-05-19 15:39:22 发布

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

我想有一个程序,它接收用户的输入,然后尝试打开该文件/程序。我可以用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


Tags: 文件import程序input参数argsordercall
1条回答
网友
1楼 · 发布于 2024-05-19 15:39:22

在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))

相关问题 更多 >