Skip to main content
 首页 » 编程设计

python之在后台执行命令

2025年05月04日12lexus

尝试使用 pythons 命令模块在后台执行 shell 命令

>>>import commands 
>>>output = commands.getstatusoutput("find / > tmp.txt &") 
   sh: Syntax error: ";" unexpected 

谁能解释语法有什么问题?那应该怎么执行呢?

塔齐姆。

请您参考如下方法:

根据getstatusoutput documentation , commands.getstatusoutput(cmd) 执行为

{ cmd  ; } 2>&1 

所以你的命令就像它一样运行

{ find / > tmp.txt & ; } 2 >& 1 

并且 ; 在此类命令中的 & 之后无效。

你应该使用 subprocess module模拟旧式 os.spawn 命令。

尝试

subprocess.Popen("find / > tmp.txt", shell=True)