簡體   English   中英

從用戶獲取輸入然后使用子流程啟動流程

[英]Getting input from user then starting a process with subprocess

我想要一個程序,它接受用戶的輸入,然后嘗試打開該文件/程序。 我可以使用 subprocess.call([file]) 來做到這一點,但這僅適用於記事本等基本程序。 如果有任何參數,我還希望能夠將參數傳遞給程序。 如:

簡單的程序(我已經實現/嘗試過)

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM