在自己的脚本中捕获 Python 的 shell 命令

从shell中启动一个带有多个参数(使用argparse)的假设Python脚本,比方说,我想从自己的脚本中捕获这个shell命令并将其放在字符串变量中。python my_script.py --foo 7.4 --bar whatever

当然,我可以通过将该对象转换为字典来保存这些参数:.但我不想那样。我想要的是将整个 shell 命令作为字符串获取。args = parser.parse_args()args_dict = vars(args)python my_script.py --foo 7.4 --bar whatever

这可能吗?如果没有,我仍然可以获得shell命令,并在将其保存在文件中时将其作为输出的一部分?python my_script.py --foo 7.4 --bar whatever >> my_output.txt


慕码人2483693
浏览 89回答 1
1回答

翻阅古今

它并不完全准确,但你可以这样推断:import sysprint ("%s %s" % (sys.executable, " ".join(sys.argv) ) )❯ python3 test.py --foo 7.4 --bar=whatever/usr/bin/python3 test.py --foo 7.4 --bar=whatever这不会捕获管道等,只会调用python的命令:❯ python3 test.py | cat/usr/bin/python3 test.py
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python