无法使用python子进程模块使用*运行shell命令

Bhu*_*ant 1 python linux shell subprocess

我无法使用包含*登录命令的python子进程模块运行任何命令.我这样用来打电话,

 subprocess.Popen(
            'cp /etc/varnida_sys/* /tmp/bucket/'.split(),
            stdout=subprocess.PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)

为此,我得到了,

cp: cannot stat ‘/etc/varnida_sys/*’: No such file or directory
Run Code Online (Sandbox Code Playgroud)

为什么会出现此错误,/ etc/varnida_sys/genders中有一个文件

我的调查表明,使用像*这样的正则表达式需要一些特殊处理.我在包含*的所有命令中遇到一些错误.

PS.当我从远程主机通过paramiko运行相同的命令时,我没有收到错误.

Eug*_*ash 6

*只有shell(将其扩展为文件列表)才能理解,您需要传递shell=True给它Popen().此外,没有必要拆分命令,你可以使用一个字符串:

subprocess.Popen("cp /etc/varnida_sys/* /tmp/bucket/",
                 stdout=subprocess.PIPE, shell=True).communicate()[0]
Run Code Online (Sandbox Code Playgroud)

正如@triplee在下面建议的那样,最好为此任务使用一些便利包装器,例如subprocess.call():

subprocess.call("cp /etc/varnida_sys/* /tmp/bucket/", shell=True)
Run Code Online (Sandbox Code Playgroud)