社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用sed命令的python[复制]

jigarshah • 5 年前 • 1399 次点击  

我在命令行中的操作:

cat file1 file2 file3 > myfile

我想用python做什么:

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40823
 
1399 次点击  
文章 [ 5 ]  |  最新文章 5 年前
wyx
Reply   •   1 楼
wyx    9 年前
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')

当你使用 子过程 ,必须终止进程。这是一个示例。如果不终止进程, 文件 会是空的,你什么也看不到。它可以继续运行 窗户 。我无法确保它可以在Unix上运行。

DJJ
Reply   •   2 楼
DJJ    10 年前

一个有趣的例子是通过在一个文件上附加类似的文件来更新它。这样就不必在进程中创建新文件。在需要附加大文件的情况下,它特别有用。这里有一种直接从python使用teminal命令行的可能性。

import subprocess32 as sub

with open("A.csv","a") as f:
    f.flush()
    sub.Popen(["cat","temp.csv"],stdout=f)
SingleNegationElimination
Reply   •   3 楼
SingleNegationElimination    14 年前

@poltos我想加入一些文件,然后处理结果文件。我认为用猫是最简单的选择。有更好的/蟒蛇式的方法吗?

当然:

with open('myfile', 'w') as outfile:
    for infilename in ['file1', 'file2', 'file3']:
        with open(infilename) as infile:
            outfile.write(infile.read())
Ryan Thompson
Reply   •   4 楼
Ryan Thompson    10 年前

要回答最初的问题,要重定向输出,只需传递 stdout 论证 subprocess.call :

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

但正如其他人指出的,外部命令的使用 cat 为了这个目的完全是无关的。

Marcelo Cantos
Reply   •   5 楼
Marcelo Cantos    9 年前

更新:不鼓励使用os.system,尽管它在python 3中仍然可用。


使用 os.system :

os.system(my_cmd)

如果您真的想使用subprocess,下面是解决方案(主要是从subprocess的文档中提取的):

p = subprocess.Popen(my_cmd, shell=True)
os.waitpid(p.pid, 0)

哦,你可以完全避免系统调用:

import shutil

with open('myfile', 'w') as outfile:
    for infile in ('file1', 'file2', 'file3'):
        shutil.copyfileobj(open(infile), outfile)