subprocess.run(['python', '/path/to/other_directory/other_code.py', 'arg1', 'arg2'], capture_output=True, text=True) 传参 只能传名称 无法传内容
时间: 2024-01-16 14:02:05 浏览: 20
对不起,我之前的回答有误导。`subprocess.run()` 函数可以传递参数内容,不仅仅是参数的名称。以下是正确的方式来传递参数内容:
```python
import subprocess
import json
# 参数内容
arg1 = "value1"
arg2 = "value2"
# 构造命令列表
command = ['python', '/path/to/other_directory/other_code.py', arg1, arg2]
# 运行其他目录的 Python 文件并传递参数
result = subprocess.run(command, capture_output=True, text=True)
# 获取输出
output = result.stdout
# 打印输出
print(output)
```
在这个例子中,`arg1` 和 `arg2` 是参数的内容,而不仅仅是参数的名称。然后,我们将这些参数内容添加到了 `command` 列表中,作为要运行的 Python 文件的命令行参数。这样,运行 `subprocess.run(command)` 就能正确地传递参数内容给其他目录的 Python 文件了。
请注意,传递给 `subprocess.run()` 的参数必须是字符串类型。如果要传递 JSON 参数,你可以使用 `json.dumps()` 将 JSON 对象转换为字符串,并在其他 Python 文件中使用 `json.loads()` 将其解析回 JSON 对象。
相关问题
如何使用python中的subprocess.Popen运行/root/fwbot/autosend.py
你可以使用以下代码在Python中调用subprocess.Popen运行/root/fwbot/autosend.py:
import subprocess
proc = subprocess.Popen(['/usr/bin/python', '/root/fwbot/autosend.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
print(out.decode('utf-8')) # print输出stdout
print(err.decode('utf-8')) # print输出stderr
subprocess.run(['python', 'path/to/st-attention.py', video.path])
这行代码使用了 Python 的 subprocess 模块来运行一个外部命令,即在命令行中执行 "python path/to/st-attention.py video.path"。其中,"python" 是要执行的命令,"path/to/st-attention.py" 是要执行的 Python 脚本的路径,"video.path" 是作为参数传递给脚本的视频路径。通过这种方式,可以在 Python 中方便地调用命令行工具,并且可以将其输出作为字符串或字节流捕获并处理。