Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.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是否使用shell从变量目录复制变量文件_Python_Shell_Copy - Fatal编程技术网

Python是否使用shell从变量目录复制变量文件

Python是否使用shell从变量目录复制变量文件,python,shell,copy,Python,Shell,Copy,我有以下python代码,它试图从变量目录dir复制存储在变量file中的文件。我还尝试将这些变量作为shell变量传递,然后也可以使用shell命令进行复制 这两种都可能吗?那么请修改我的密码 import os import shutil import subprocess dir='somedir' file='somefile' # Now I want to get $dir as a shell variable and copy the file to # my pres

我有以下python代码,它试图从变量目录
dir
复制存储在变量
file
中的文件。我还尝试将这些变量作为shell变量传递,然后也可以使用shell命令进行复制

这两种都可能吗?那么请修改我的密码

import os
import shutil
import subprocess


dir='somedir'
file='somefile'

# Now I want to get $dir as a shell variable and copy the file to
#   my present directory

os.system("echo $dir")
os.system("cp $dir/$file .")

# I want to copy dir/file to the present directory

shutil.copy(dir/file,file) # Following shutil.copy(src,dest) format
shutil.copyfile(dir/file,file)

您可以在Python中简单地执行此操作,如下所示:-

import os
import shutil

dir = 'somedir'
file = 'somefile'
file_to_copy = dir + "/" + file
current_location = os.getcwd()
shutil.copy(file_to_copy, current_location)

现在,位置
somedir
中的文件
somefile
将被复制到当前目录位置。

可能的重复;字符串格式是否有其他副本?可能的副本不要使用
os.system
复制文件。为什么要使用一个依赖于平台的解决方案,而您可以直接使用python呢?无论如何,您的
shutil.copy(dir/file,file)
的问题是
dir/file
无效。你不能分割字符串。使用
os.path.join
将它们组合成文件路径。使用字符串格式
os.system(“echo${}”.format(dir))os.system(“cp${}/${}.”.format(dir,file))
更多信息