从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
1 回答

翻阅古今
TA贡献1780条经验 获得超5个赞
它并不完全准确,但你可以这样推断:
import sys
print ("%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
添加回答
举报
0/150
提交
取消