import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program
5 回答
206
size = 'ffprobe -v error -show_entries format=size -of default=noprint_wrappers=1:nokey=1 dump.mp4 > file'
proc = subprocess.Popen(shlex.split(size), shell=True)
time.sleep(1)
proc.terminate() #proc.kill() modify it by a suggestion
size = ""
with open('file', 'r') as infile:
for line in infile.readlines():
size += line.strip()
print(size)
os.remove('file')
# Use a list of args instead of a string
input_files = ['file1', 'file2', 'file3']
my_cmd = ['cat'] + input_files
with open('myfile', "w") as outfile:
subprocess.call(my_cmd, stdout=outfile)
5 回答
当你使用 subprocess 时,必须杀死进程 . 这是一个例子 . 如果你不杀死进程, file 将为空,你什么都不读 . 它可以在 Windows 上运行 . 我不能确保它可以在Unix上运行 .
要回答原始问题,要重定向输出,只需将
stdout
参数的打开文件句柄传递给subprocess.call
:但正如其他人所指出的那样,为此目的使用像
cat
这样的外部命令是完全无关紧要的 .一个有趣的案例是通过向其添加类似文件来更新文件 . 然后,不必在此过程中创建新文件 . 在需要附加大文件的情况下,它特别有用 . 这是直接从python使用teminal命令行的一种可能性 .
当然:
更新:不鼓励使用os.system,尽管仍然可以在Python 3中使用 .
使用
os.system
:如果你真的想使用子进程,这里的解决方案(主要取自子进程的文档):
OTOH,你可以完全避免系统调用: