我想编写一个函数来执行shell命令并将其输出作为字符串返回,无论是错误还是成功消息.我只想获得与命令行相同的结果.
什么是代码示例会做这样的事情?
例如:
def run_command(cmd):
# ??????
print run_command('mysqladmin create test -uroot -pmysqladmin12')
# Should output something like:
# mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
Run Code Online (Sandbox Code Playgroud) 如何使用subprocess.call()?获取进程的输出?
传递StringIO.StringIO对象stdout会出现此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call
return Popen(*popenargs, **kwargs).wait()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 588, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 945, in _get_handles
c2pwrite = stdout.fileno()
AttributeError: StringIO instance has no attribute 'fileno'
>>>
Run Code Online (Sandbox Code Playgroud) 我用subprocess模块调用不同的进程.但是,我有一个问题.
在以下代码中:
callProcess = subprocess.Popen(['ls', '-l'], shell=True)
Run Code Online (Sandbox Code Playgroud)
和
callProcess = subprocess.Popen(['ls', '-l']) # without shell
Run Code Online (Sandbox Code Playgroud)
两者都有效.阅读文档后,我开始知道这shell=True意味着通过shell执行代码.这意味着在缺席的情况下,该过程将直接启动.
那么我应该更喜欢我的情况 - 我需要运行一个进程并获得其输出.从shell内部或外部调用它有什么好处.
我想subprocess.check_output()用ps -A | grep 'process_name'.我尝试了各种解决方案,但到目前为止没有任 有人可以指导我怎么做吗?
我想pythong使用子进程模块运行命令,并将输出存储在变量中.但是,我不希望将命令的输出打印到终端.对于此代码:
def storels():
a = subprocess.Popen("ls",shell=True)
storels()
Run Code Online (Sandbox Code Playgroud)
我在终端中获取目录列表,而不是将其存储在a.我也尝试过:
def storels():
subprocess.Popen("ls > tmp",shell=True)
a = open("./tmp")
[Rest of Code]
storels()
Run Code Online (Sandbox Code Playgroud)
这也会将ls的输出打印到我的终端.我甚至尝试过这个有点过时的os.system方法的命令,因为ls > tmp在终端中运行根本不会打印ls到终端,而是存储它tmp.但是,同样的事情发生了.
编辑:
遵循marcog的建议后,我得到以下错误,但仅在运行更复杂的命令时.cdrecord --help.Python吐了出来:
Traceback (most recent call last):
File "./install.py", line 52, in <module>
burntrack2("hi")
File "./install.py", line 46, in burntrack2
a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE)
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child
raise child_exception
OSError: [Errno …Run Code Online (Sandbox Code Playgroud) 我想从像一些shell命令得到的输出ls或者df在Python脚本.我看到它commands.getoutput('ls')已被弃用,但subprocess.call('ls')只会给我返回代码.
我希望有一些简单的解决方案.
我想做subprocess.call,并将调用的输出变为字符串.我可以直接执行此操作,还是需要将其传输到文件中,然后从中读取?
换句话说,我可以以某种方式将stdout和stderr重定向到字符串中吗?
我想在这里捕获输出.如果,在python提示符下,我运行
p = subprocess.Popen(["/path/to/search_by_hash.par", hash_str],
stdout=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)
返回值(列表)打印到stdout,但未捕获
[4460475, 4406612, 4379510]
Run Code Online (Sandbox Code Playgroud)
我试过跟进它
value = p.communicate()[0]
value
Run Code Online (Sandbox Code Playgroud)
..but值是一个空字符串,而不是我期望的整数列表,并且正在打印到stdout
我试验了子进程的Store输出的解决方案.Popen调用字符串但是无法捕获输出.
更新:
stderr似乎也没有产生任何东西......我正在寻找的列表正在被打印出来......只是没有任何运气来捕获它.见下文:
>>> p = subprocess.Popen(["/home/jfry/tools/search_by_hash.par", hash_str],
stdout=subprocess.PIPE)
>>>
[4460475, 4406612, 4379510]
value, err = p.communicate()
>>> value
''
>>> err
Run Code Online (Sandbox Code Playgroud)
谢谢!
使用以下命令,它将打印'640x360'
>>> command = subprocess.call(['mediainfo', '--Inform=Video;%Width%x%Height%',
'/Users/Desktop/1video.mp4'])
640x360
Run Code Online (Sandbox Code Playgroud)
我如何设置一个等于输出字符串的变量,所以我可以得到x='640x360'?谢谢.
我正在尝试使用以下代码捕获命令的输出:
lines = subprocess.run(['ffmpeg', '-hide_banner', '-nostats', '-i', in_filename, '-vn', '-af', 'silencedetect=n={}:d={}'.format(silence_threshold, silence_duration), '-f', 'null', '-'], capture_output=True, text=True, shell=True, check=True, encoding='utf-8').stdout
print (lines)
Run Code Online (Sandbox Code Playgroud)
但lines是一个空字符串并且没有打印任何内容。删除后capture_output=True,将显示正确的输出(不打印)。
我测试了许多组合,包括删除所有subprocess.run参数并仅包含capture_output=True相同的结果。
我还用很少的参数进行了测试,举了一个最小的例子:subprocess.run(['ffmpeg', '-version'], capture_output=True, text=True, shell=True, check=True, encoding='utf-8').stdout
还进行了测试stdout=subprocess.PIPE并stderr=subprocess.PIPE作为subprocess.run参数而不是capture_output=True
我不明白发生了什么事。提前致谢!
python ×10
subprocess ×9
pipe ×3
shell ×2
command ×1
ffmpeg ×1
linux ×1
python-2.6 ×1
stringio ×1