V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
18870715400
V2EX  ›  Python

询问大佬们一个 shell 脚本的问题

  •  
  •   18870715400 · 2021-11-01 17:05:31 +08:00 · 1979 次点击
    这是一个创建于 878 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如有一个 result.txt 文件

    python3 test.py --name=$name
    

    test.py 文件

    import argparse
    
    
    class Config:
        parser = argparse.ArgumentParser()
        parser.add_argument("--name")
    
        args = parser.parse_args()
        name = args.name
        print("name is %s" % name)
    
    
    if __name__ == '__main__':
        config = Config()
    
    

    我在 终端执行命令,

    name="hello world"
    cmd=$(cat result.txt)
    echo $cmd
    $cmd
    

    结果如下, 就是 name 这个变量没有传递进去脚本里面,请问一下应该如何改才能将这个 name 变量传递进去呀

    python3 test.py --name=$name
    name is $name
    
    11 条回复    2021-11-20 10:16:19 +08:00
    thedrwu
        1
    thedrwu  
       2021-11-01 17:07:54 +08:00 via Android
    eval
    liangqing
        2
    liangqing  
       2021-11-01 17:16:16 +08:00
    直接把 result.txt 当脚本用
    ```bash
    sh result.txt
    ```
    18870715400
        3
    18870715400  
    OP
       2021-11-01 17:21:05 +08:00
    @liangqing , 好的, 谢谢大佬
    AoEiuV020
        4
    AoEiuV020  
       2021-11-01 17:21:14 +08:00
    第一反应是 envsubst ,但你这里感觉问题不只一个,
    cat 再$cmd 为什么不直接 sh result.txt 这种只要 export name 就能传进去了,
    name 变量内容带空格的话后续所有使用都要用好双引号,否则一个变量会被当成两个参数,
    jhsea3do
        5
    jhsea3do  
       2021-11-01 17:22:15 +08:00
    main.sh

    #!/bin/sh
    python3 test.py "$@"



    sh main.sh --name=123

    这样满足你要球吗
    18870715400
        6
    18870715400  
    OP
       2021-11-01 17:27:35 +08:00
    @AoEiuV020 嗯, 是我想复杂了, 直接 sh 对应的脚本就行了, 还有, 我试了一下, 无论加不加单引号或者双引号 name 变量的值都是穿不进去的
    superrichman
        7
    superrichman  
       2021-11-01 17:31:13 +08:00
    引号

    name="hello world"
    python3 test.py --name="$name"
    superrichman
        8
    superrichman  
       2021-11-01 17:35:43 +08:00
    ruanimal
        9
    ruanimal  
       2021-11-01 17:45:35 +08:00
    把类换成函数就好了,不懂就别瞎用。。。
    ruanimal
        10
    ruanimal  
       2021-11-01 17:47:22 +08:00
    @ruanimal 看错了,丢人。。
    canwushuang
        11
    canwushuang  
       2021-11-20 10:16:19 +08:00
    指令用了 python 的解释器,但是又用了 shell 的代码 $name 是不是有些问题?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   958 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:15 · PVG 05:15 · LAX 14:15 · JFK 17:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.