如何在具有python函数(python.sysv)的python中使用linux命令

时间:2019-06-24 18:21:27

标签: python bash

在我的python脚本中,我需要使用“ awk”,但我想使用sys.argv传递文件。 我当前的代码是这样的:

import sys
import os

cmd="awk '/regex/ {print}' sys.argv[1] | sed 's/old/new/g'"
x=os.popen(cmd).read()

现在的问题是'sys.argv'是python,但是cmd变量正在使用linux命令。 所以我的问题是-有什么办法可以在我的linux命令中包含sys.argv吗?

3 个答案:

答案 0 :(得分:2)

您实际上不需要Awk或@import (reference) '~@internal_repo/components/sass/colors/colors.scss'; .common-header { height: 100%; width: 100%; background-color: @asquid-ink; } 。 Python可以原生,优雅,灵活,强大,自然地完成这些事情。

sed

如果您确实真的想对某些子过程使用子过程,只需使用Python的常规字符串插值函数,在其中需要将Python变量的值插入字符串中。

import sys
import re

r = re.compile(r'regex')
s = re.compile(r'old')

with open(sys.argv[1]) as input:
    for line in input:
        if r.search(line):
            print(s.sub('new', line))

但实际上,不要这样做。如果您确实无法避免子流程,请使其尽可能简单(避免使用import subprocess import sys import shlex result = subprocess.run( """awk '/regex/ {print}' {} | sed 's/old/new/g'""".format(shlex.quote(sys.argv[1])), stdout=subprocess.PIPE, shell=True, check=True) print(subprocess.stdout) 并剥离所有可以在Python中完成的部分)。

答案 1 :(得分:1)

只是尝试这样

cmd="awk '/regex/ {print}' " + str(sys.argv[1]) + " | sed 's/old/new/g'"
x=os.popen(cmd).read()

答案 2 :(得分:0)

the answer by @tripleee的第一部分所述,您的最佳选择是将您的逻辑实现为纯Python逻辑。您的第二个最佳选择是保留外部工具,但无需使用Shell来调用它们并将它们连接在一起。

请参见Python文档部分Replacing Shell Pipelines

import sys
from subprocess import Popen, PIPE

p1 = Popen(['awk', '/regex/ {print}'], stdin=open(sys.argv[1]), stdout=PIPE)
p2 = Popen(['sed', 's/old/new/g'], stdin=p1.stdout, stdout=PIPE)
x = p2.communicate()[0]

您的第三最佳选择是保留外壳,但将代码中的数据带外传递:

p = subprocess.run([
  """awk '/regex/ {print}' <"$1" | sed 's/old/new/'""",  # code to run
  '_',                                                   # $0 in context of that code
  sys.argv[1]                                            # $1 in context of that code
], shell=True, check=True, stdout=subprocess.PIPE)
print(p.stdout)