写作操作系统输出到fi

2024-06-16 12:24:19 发布

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

基本上,我想输出操作系统结果基于系统argv输入。代码见下文。它抛出了一个错误:SyntaxError:invalid syntax。我的猜测是output操作符不接受变量?在

#!/usr/bin/python
import os
import sys
nfile = sys.argv[1]
intfile=('/folder/folder/%s/%s.txt' % (nfile, nfile)) 

if os.path.isfile(intfile): # if file exist remove
    os.remove(intfile)
else: 
    os.system('sudo ovs-vsctl list-ports %s > %s' % (nfile, intfile)

Tags: 代码importifos系统错误sysfolder
1条回答
网友
1楼 · 发布于 2024-06-16 12:24:19

os.system不受欢迎。subprocess模块与os.system()一样干净、安全且功能强大。在

import subprocess
with open(intfile, 'w') as outfile:
    subprocess.call(['sudo', 'ovs-vsctl', 'list-ports', nfile], stdout=outfile)

相关问题 更多 >