我想在批处理文件和python程序之间建立连接。
我想使用python来获取一个参数“abc”,让批处理文件使用参数“abc”来做其他事情。
如何在python中将参数返回到命令行?
感谢您的帮助。
答案 0 :(得分:5)
您不会说出您正在使用的环境(* nix / Windows / OSX等),但对于* nix和shell脚本,您可以这样做
# Python
# whatever.py
import sys
sys.stdout.write('abc')
sys.exit(0)
# In your shell
OUT=`python whatever.py`
echo $OUT
# Will print abc, and it's stored in the variable `OUT` for later consumption.
编辑(适用于Windows):
# Python
# whatever.py
import sys
sys.stdout.write('abc')
sys.exit(0)
# In a .bat file, or cli.
python whatever.py > temp.txt
set /p OUT=<temp.txt
# Creates/replaces a file called temp.txt containing the output of whatever.py
# then sets the `OUT` var with the contents of it.
不幸的是,Windows的做法并不像* nix那样漂亮和整洁。
答案 1 :(得分:0)
在shell中,您始终可以使用-c
开关执行单次运行的任何命令。为了更好地解释,它以python脚本的形式执行字符串。所以简而言之它运行python终端,执行然后终止python终端。就那么简单。现在让我举几个例子来澄清
请记住我使用带有cmd终端的Windows 10计算机
python -c "print(__name__)"
返回__main__
值,因为我当前处于命令提示符下。现在这很棒,因为python在每一行之后支持多行使用; ,所以你理论上可以把整个脚本写成文本文件,而不是用安装了正确版本的python的python -c
执行它。
因此,如果您愿意,可以通过这种方式轻松完成python -c "import sys;sys.stdout.write('abc')"
。
现在把它保存到命令变量中,我只想出了一条不好的方法,但如果有人有另一条方式。请评论。
python -c "import string;print(dir(string))" >> text.txt
set /p drStr= < text.txt
del text.txt
或者是大规模的oneliner:
python -c "import string;print(dir(string))" >> text.txt && set /p drStr= <text.txt && del text.txt
现在只需输入set drStr
打印出变量即可。