【发布时间】:2020-11-12 06:40:16
【问题描述】:
我正在为 SQL 表开发一个简单的 Tkinter GUI。显然,我不得不使用 shell 命令,并且一直在为子进程 shell 系统而苦苦挣扎。
例如,subprocess.check_output('ls') 将运行 ls,但要运行 ls -l,则需要使用 subprocess.check_output(['ls', '-l'])。我还没有找到一种方法来获取更复杂命令的输出,例如cat test.sql | sqlite3 test.db(在test.db 上运行sqlite3,然后在提示符处列出test.sql)。
我尝试过的事情
-
subprocess.check_output(['cat', 'test.sql', '|', 'sqlite3', 'test.db'])错误(在 Python shell 上运行):
cat: '|': No such file or directory cat: sqlite3: No such file or directory Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.7/subprocess.py", line 395, in check_output **kwargs).stdout File "/usr/lib/python3.7/subprocess.py", line 487, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command '['cat', 'test.sql', '|', 'sqlite3', 'test.db']' returned non-zero exit status 1. -
subprocess.check_output([['cat', 'test.sql'], '|', ['sqlite3', 'test.db']])(不知道为什么我期望它会起作用)错误:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.7/subprocess.py", line 395, in check_output **kwargs).stdout File "/usr/lib/python3.7/subprocess.py", line 472, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.7/subprocess.py", line 775, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.7/subprocess.py", line 1436, in _execute_child executable = os.fsencode(executable) File "/usr/lib/python3.7/os.py", line 809, in fsencode filename = fspath(filename) # Does type-checking of `filename`. TypeError: expected str, bytes or os.PathLike object, not list -
使用
bash -c命令:subprocess.check_output(['bash', '-c', '"cat test.sql | sqlite3 test.db"'])错误:
bash: cat test.sql | sqlite3 test.db: command not found Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.7/subprocess.py", line 395, in check_output **kwargs).stdout File "/usr/lib/python3.7/subprocess.py", line 487, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command '['bash', '-c', '"cat test.sql | sqlite3 test.db"']' returned non-zero exit status 127.(请注意,单独运行
bash -c "cat test.sql | sqlite3 test.db"效果很好。)
我最终只使用了os.system() 和os.popen() 命令,但人们说不推荐使用这些命令。我该怎么办?
【问题讨论】:
标签: python bash subprocess