使用参数从 bash 调用 Python 脚本 [英] Call Python script from bash with argument

查看:41
本文介绍了使用参数从 bash 调用 Python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用以下命令从我的 bash 脚本运行 python 脚本:

I know that I can run a python script from my bash script using the following:

python python_script.py

但是如果我想将一个变量/参数从我的 bash 脚本传递给我的 python 脚本呢?我该怎么做?

But what about if I wanted to pass a variable / argument to my python script from my bash script. How can I do that?

基本上 bash 会计算出一个文件名,然后 python 会上传它,但我需要在调用它时将文件名从 bash 发送到 python.

Basically bash will work out a filename and then python will upload it, but I need to send the filename from bash to python when I call it.

推荐答案

要在 bash 脚本中执行 python 脚本,您需要调用与在终端中相同的命令.例如

To execute a python script in a bash script you need to call the same command that you would within a terminal. For instance

> python python_script.py var1 var2

要在 python 中访问这些变量,您需要

To access these variables within python you will need

import sys
print sys.argv[0] # prints python_script.py
print sys.argv[1] # prints var1
print sys.argv[2] # prints var2

这篇关于使用参数从 bash 调用 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆