社区所有版块导航
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

如何在同一个python程序中将python变量传递给bash代码?

c_risk • 7 年前 • 2221 次点击  

我已经编写了一个python代码来检查文件是否存在于hadoop文件系统中。python函数接收从另一个函数传递的位置,并在检查中检查bash代码是否存在该位置。

    def check_file_exists_in_hadoop(loc):
        yourdir = "/somedirectory/inhadoop/"+loc
        cmd = '''
        hadoop fs -test -d ${yourdir};
        if [ $? -eq 0 ]
        then 
            echo "Directory exists!"
        else
            echo "Directory does not exists!" 
        fi
        '''
        res = subprocess.check_output(cmd, shell=True)
        output = (str(res, "utf-8").strip())
        print(output)
        if output == "Directory exists!":
            print("Yay!!!!")
        else:
            print("Oh no!!!!") 

如何在代码的bash部分中传递“yourdir”变量。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40670
文章 [ 2 ]  |  最新文章 7 年前
Gilles
Reply   •   1 楼
Gilles    7 年前

将字符串作为参数传递给shell。而不是使用 shell=True 运行 ['sh', '-c', cmd] 在引擎盖下,显式调用shell。在shell代码之后,第一个参数是shell或脚本名(此处未使用),然后下一个参数作为 "$1" 在shell片段中,下一个参数为 "$2" 等。

cmd = '''
    hadoop fs -test -d "$1";
…
'''
res = subprocess.check_output(['sh', '-c', cmd, 'sh', yourdir])

或者,将字符串作为环境变量传递。

cmd = '''
    hadoop fs -test -d "$yourdir";
…
'''
env = os.environ.copy()
env['yourdir'] = yourdir
res = subprocess.check_output(cmd, shell=True, env=env)

在shell片段中,注意 double quotes around $1 or $yourdir .

不要直接将字符串插入shell命令,也就是说,不要使用 'test -d {}'.format(yourdir) . 如果字符串包含shell特殊字符,则这不起作用:这是一个巨大的安全漏洞。例如,如果 yourdir 是 a; rm -rf ~ 然后你就和你的数据吻别了。

tripleee
Reply   •   2 楼
tripleee    7 年前

在贝壳里玩耍看起来很尴尬,为什么不干脆:

def check_file_exists_in_hadoop(loc):
    path = "/somedirectory/inhadoop/" + loc
    res = subprocess.run(["hadoop", "fs", "-test", "-d", path])
    return res.returncode == 0

您可以执行为:

if check_file_exists_in_hadoop('foo.txt'):
    print("Yay!!!!")
else:
    print("Oh noes!!!!")

在类unix系统中执行/运行进程/程序时,它会收到一组参数(例如, sys.argv 在python中)。你可以用不同的方法来构造它们,但是把它们传递给 run 给你最直接的控制。当然可以使用shell来执行此操作,但仅启动shell来执行此操作似乎没有必要。假设这个参数列表只是python中字符串的列表,那么可以使用普通的list/string操作来构造所需的任何内容。

使用shell可能很有用,但正如gilles所说,您需要小心地清理/逃避您的输入,并不是每个人都喜欢 little bobby tables !