Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用python运行多行cmd命令_Python 3.x_Cmd - Fatal编程技术网

Python 3.x 使用python运行多行cmd命令

Python 3.x 使用python运行多行cmd命令,python-3.x,cmd,Python 3.x,Cmd,我正在尝试使用python运行cmd代码 p = 'calcifer --config="C:\\Users\\yilin.chen\\Desktop\\pythonminingstuff\\calcifer\\calcifer\\pipelines\\run_config.yaml"' subprocess.call('cd C:\\Program Files (x86)\\Olympus\\Vanta\\bin', shell = True) subprocess.call(p, shell

我正在尝试使用python运行cmd代码

p = 'calcifer --config="C:\\Users\\yilin.chen\\Desktop\\pythonminingstuff\\calcifer\\calcifer\\pipelines\\run_config.yaml"'
subprocess.call('cd C:\\Program Files (x86)\\Olympus\\Vanta\\bin', shell = True)
subprocess.call(p, shell = True)
后来我发现,这两行代码应该一起运行。所以我试过了

commands = """ SET foo=1 | SET foo=2 | echo %foo% """
b = subprocess.check_output(commands, shell=True)
print(b.decode('ascii'))
这是作为指南贴在这里的 但这对我不起作用。上面的代码只执行打印%foo%的最后一行。如果复制并粘贴原始代码,它只打印“hello”


有什么想法吗?感谢您的帮助。

您尝试执行的第一个命令似乎是将
cd
放入目录,这可以通过在中设置
cwd
参数来实现

举个小例子,我将
echo
二进制文件复制到
/Users/Samuel/tmp/eecchhoo
。如果我尝试进入目录,然后在两个子进程调用中调用二进制文件,我将失败,如您所述:

>>> import subprocess
>>> subprocess.call('cd /Users/Samuel/tmp', shell=True)
0
>>> subprocess.call('./eecchhoo helloworld', shell=True)
/bin/sh: ./eecchhoo: No such file or directory
127
但是,通过将
cwd
参数设置为所需的值,我可以使调用成功:

>>> import subprocess
>>> subprocess.call('./eecchhoo helloworld', shell=True, cwd='/Users/Samuel/tmp')
helloworld
0
如果需要运行其他命令(不仅仅是更改工作目录),可以参考以下答案:。

使用“&&”运算符。
例如:

p = 'calcifer --config="C:\\Users\\yilin.chen\\Desktop\\pythonminingstuff\\calcifer\\calcifer\\pipelines\\run_config.yaml"'
subprocess.call('cd C:\\Program Files (x86)\\Olympus\\Vanta\\bin && ' + p, shell = True)
subprocess.call(p, shell = True)

您还可以使用os.system(命令)执行完全相同的操作:

import os
p = 'calcifer --config="C:\\Users\\yilin.chen\\Desktop\\pythonminingstuff\\calcifer\\calcifer\\pipelines\\run_config.yaml"'
os.system('cd C:\\Program Files (x86)\\Olympus\\Vanta\\bin && ' + p)



您可以阅读更多有关它的信息。

我猜您假定
|
字符是一个命令分隔符?这太神奇了。但是,如果我要执行两个“echo”,我该怎么办?@ChenLin您可以像您那样使用
子流程。调用
,但您需要正确区分不同的命令。在我的平台(Mac OS)上,我可以使用
&&
(“and”operator)或
(“或”操作符):
子流程调用('echo hello&&echo world',shell=True)
子流程调用('echo hello;echo world',shell=True)
都可以。我试过了,成功了,非常感谢您的帮助。我真的很感激。