从python向bash发送变量

2024-10-03 17:15:10 发布

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

我已经尽我最大的努力去研究,我已经到了使用子流程和subprocess.call帮助我将python变量发送到bash。我设法从bash输出中获取python变量,但现在我需要这些变量保持同步。我环顾四周都学不到怎么用subprocess.call有效的。我一直在使用subprocess.check_输出将bash输出完美地转换成python变量。我有困难明白subprocess.call接受参数以及如何正确使用它。我试着遵循我认为正确的格式。 这是我的密码。P、 S我是一个全新的加入这个论坛虽然我已经使用它的吨有用的信息多年。我不知道如何格式化我的代码输入看起来像我在这里看到的一样。不管怎样,我确定你可以原谅我,因为我尝试了“代码”“方块引号”等按钮。在

###BEGINING OF CODE###
#! /usr/bin/env python2
import os,time,subprocess

#GRAB DATA
os.system('ifconfig > /tmp/ifconfig.txt;clear;cat /tmp/ifconfig.txt|grep "wlan"|cut -c 1-5 > /tmp/dev.lst;clear;')

#SET allwlan
allwlan=subprocess.check_output("cat /tmp/dev.lst", shell=True)

#SET max_index VARIABLE
max_index=subprocess.check_output("wc -l < /tmp/dev.lst", shell=True)

#SET curwlan WLAN LINE
#os.system(echo 2 > /tmp/curline.lst)

#STRIP DATA FOR curwlan
subprocess.call(['head', '-2', '/tmp/dev.lst', stdout=subprocess.PIPE, shell=True'])
#NEED#HELP#HERE# subprocess.call(['tail', '-1', > /tmp/curwlan.lst;')

#SET curwlan VARIABLE
curwlan=subprocess.check_output("cat /tmp/curwlan.lst", shell=True)

##STRIP EXCESS  CHARACTERS/EMPTY LINES FROM VARIABLES##
curwlan=str(curwlan)
splitted=curwlan.split()
curwlan=splitted[0]
allwlan=allwlan[:-1]
splitted=max_index.split()
max_ index=splitted[0]
max_index=int(max_index)

##DEBUG MODE
print("Welcome, ")
print("     to debug mode. wireless adapter decting algorithm")
print
print("ALLWLAN:")
print(allwlan)
print
print("CURWLAN:")
print(curwlan)
print
print("MAX_INDEX:")
print(max_index)
print
input("PRESS ENTER TO EXIT")
####END OF CODE####*

我的代码中的错误在下面 #curwlan的条带数据

这是在我添加subprocess.call命令。在

^{pr2}$

我很想学习如何让python和bash部分一起传递它们的变量,我知道我在正确的轨道上subprocess.call我已经挣扎了几天了。我正在尝试制定我自己的算法来检测我的无线网卡,并能够使用每一个(不管是多少个,也不管它们是什么名字)作为我的变量 旧的脚本,现在因为我不断变化的无线卡名称而挣扎。先谢谢,我不明白我在问什么subprocess.call去做是不现实的。在


Tags: devbashtrueindexcheckshellcalltmp
2条回答

谢谢大家的建议。我的剧本是这样的,一年多后,这是这个部分的样子

def detmon():
try:
    subprocess.call(['clear'])      
    item = []
    items = []
    the_choice = []

    iwconfig = subprocess.check_output(['iwconfig'])
    for line in iwconfig.split():
     if "mon" in line:
      items.append(line.strip(':'))
    subprocess.call(['clear'])
    max_index=len(items)-1
    #items=items[counter]

    #Print Files List
    for item in items:
        print(" ", items.index(item), ": ", item)
    os.system('echo "\n"')
    print(len(items))
    try:
        if len(items) >= 0: 
            counter = 0
            allmon = []
            ifconfig = subprocess.check_output(['iwconfig'])
            for line in ifconfig.split():
             if "mon" in line:
              allmon.append(line.strip(':'))
            subprocess.call(['clear'])
            max_index=len(allmon)
            curmon=allmon[counter]
            while counter <= max_index:
             curmon=allmon[counter]
             subprocess.call(['airmon-ng', 'stop', curmon])
             counter += 1
        else:
                print("No more 'mon' interfaces are found")
    except:     
            print("No more 'mon' interfaces are found")
except KeyboardInterrupt:
    pass

你应该尽量避免外部进程。您所做的大部分工作都很容易在Python中实现,并且如果在本机实现的话,将更加紧凑和高效。在

此外,您还将过时的os.system()与{}混合在一起,后者通常是首选的,正如os.system()文档中所指出的那样。在

subprocess.call()只有在您不希望命令有任何输出时才真正合适。您尝试使用它的实例,subprocess.check_output()将是正确的调用。然而,在您(据我所知,不必要的)运行shell命令并输出到临时文件的地方,您可以简单地使用subprocess.call()。在

您需要了解shell在何时何地有用和必要。在许多地方,如果没有shell,shell=True会更安全、更快、更简单、更直接。如果您只运行一个简单的硬编码命令而不重定向或全局化,那么从subprocess.whatever('command with args', shell=True)切换到{}将立即减少您的时间和内存占用,而不会产生任何不良影响。如果需要重定向、管道或globbing,也许您想要shell=True;但在许多情况下,用Python做这些事情将是简单而直接的。例如,下面是如何在没有shell的情况下编写head命令:

with open('/tmp/randomfile', 'w') as outputfile:
    subprocess.call(['head', '-n', '2', '/tmp/dev.lst'], stdout=outputfile)

不管怎样,在这些事情都不碍事的情况下,下面是我将如何做(我认为)你正在尝试的事情:

^{pr2}$

这是仓促的,但我相信我至少捕捉到了您当前的pretzel逻辑代码的大部分功能;尽管我假设在/tmp文件系统中散播随机输出文件不是脚本的一个基本特性。在

相关问题 更多 >