python - 将python脚本中的变量解析为shell
问题描述
大家好,我是使用 python 编写的新手,我正在尝试如何将变量解析到 shell 中。例如;
#!/usr/python3
import os
import subprocess
sometext = 'Hello World'
os.system("echo $sometext")
这什么都不返回,我假设这不会正确解析。但解释了我正在尝试做的事情。
我做了一些挖掘并尝试替换最后一行
#!/usr/python3
import os
import subprocess
sometext = 'Hello World'
subprocess.call('echo {sometext}')
这会吐出以下错误;
Shell % python3 pingtest.py
Traceback (most recent call last):
File "pingtest.py", line 12, in <module>
subprocess.call('echo {sometext}')
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 340, in call
with Popen(*popenargs, **kwargs) as p:
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'echo {sometext}'
解决方案
#!/usr/bin/python3
import subprocess
sometext = 'Hello World'
subprocess.call(["echo", sometext])
推荐阅读
- python - FileNotFoundError:[Errno 2] 没有这样的文件或目录:'hadoop'
- ibm-datapower - 如何使用 API 调用在 IBM Datapower 中添加加密证书
- google-bigquery - 基于组和时间戳的唯一值
- amazon-web-services - UnexpectedStatusException:培训作业 sagemaker-scikit-learnxxxx 失败。原因:AlgorithmError:框架错误
- azure-devops - 如何在 Azure devops wiki 中发布代码覆盖率和测试结果
- angular - 如何修复此错误类型错误:无法以角度读取未定义的属性(读取“长度”)
- azure - 在 Cosmos 中加入数组或非数组对象
- python - 如何在带有 Pycharm 的 WSL/WSL2 中使用 Cython?
- android - 这里Android SDK与华为的兼容性
- fetch - 当我通过请求正文发送令牌时,Slack 的 apps.connections.open 返回“invalid_auth”