我想在python 3.7.4中使用subprocess.run()
运行shell脚本和git-bash命令。当我在subprocess documentation page上运行简单示例时,会发生这种情况:
import subprocess
subprocess.run(["ls", "-l"])
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\pycharm\project\envs\lib\subprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\pycharm\project\envs\lib\subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "C:\pycharm\project\envs\lib\subprocess.py", line 1178, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
# it also fails with shell=True
subprocess.call(["ls", "-l"], shell=True)
'ls' is not recognized as an internal or external command,
operable program or batch file.
1
来自shell=True
的消息是来自Windows cmd的消息,这表明子进程未向git-bash发送命令。
我正在使用位于project/envs/
文件夹中的python的conda环境。我还安装了git-bash。
我也尝试设置环境并得到相同的错误。
import os
import subprocess
my_env = os.environ.copy()
my_env["PATH"] = 'C:\Program Files\Git\;' + my_env["PATH"]
subprocess.run(['git-bash.exe', 'ls', '-l'], env=my_env)
Traceback (most recent call last):
File "<input>", line 3, in <module>
File "C:\pycharm\project\envs\lib\subprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\pycharm\project\envs\lib\subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "C:n\pycharm\project\envs\lib\subprocess.py", line 1178, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
我可以通过指向git-bash.exe使其运行,但是它返回一个空字符串,而不是我目录中的文件
import subprocess
subprocess.run(['C:\Program Files\Git\git-bash.exe', 'ls', '-l'], capture_output=True)
CompletedProcess(args=['C:\\Program Files\\Git\\git-bash.exe', 'ls', '-l'], returncode=0, stdout=b'', stderr=b'')
[subprocess documentation page上显示的有关使此工作最佳方法的任何建议,我将不胜感激。
尝试一下
p = subprocess.Popen(("ls", "-l"), stdout=subprocess.PIPE)
nodes = subprocess.check_output(("grep"), stdin=p.stdout)
p.wait()
ls
是用于列出文件和目录的Linux shell命令dir
是Windows命令行命令,用于列出文件和目录尝试在Windows命令行中运行dir
。如果可行,请尝试使用python子进程运行相同的命令:
import subprocess
subprocess.run(["dir"])