Reputation: 2022
Use case: There is a certain file located on a remote server. Instead of hard coding the path to that file in my program I would like to be prompted by the program to let me specify the path to that directory on the remote server. This will help in program portability. I am able to connect to remote server in pyCharm 4.5 professional edition. Using SFTP to connect to remote server in pyCharm. Password or keyfile is not an issue to be concerned with at least for now.
Question: the function raw_input() works for local interpreter. But what method do I use to prompt the user to enter the directory path to a file located in a remote server?
For now I am hard-coding the file path in the program like
input_file="/home/ashish/PyCharm_proj/raw_data/all_user_and_tweets_only_raw.csv"
I also tried the following code which off course does not work when executed on the remote server
import os,sys
user_input = raw_input("Enter the path of your file (use \: ")
assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)
input_file = open(user_input,'r+')
print("Hooray we found your file!")
Similar questions are 1,2,3,4 but I could not find anything relevant that satisfies my use case. Any suggestions to solve this?
Upvotes: 0
Views: 1381
Reputation: 1225
So, the question was a bit unclear at first. OP was ultimately looking for a way to give input to his script about the location (known) of a file on a remote server.
OP tried raw_input
but got an unspecified error.
Further discussion in comments reveals the original approach was correct for this use case. The error was in an unrelated section of code, where OP used the same identifier for the input string and the file object, resulting in trying to open
the file object.
Upvotes: 1
Reputation: 453
To validate the file exists on remote host/server you need a way to connect to that host. There are many different ways depending on your situation.
So it really depends on your case.
If using paramiko, one of the easiest way is to use SFTP class. Something like this:
ssh_client = paramiko.SSHClient()
ssh_client.connect(host, port, user, password)
sftp = ssh_client.open_sftp()
file_stat = sftp.stat(path) # can use stat
try:
sftp_obj1 = sftp.file(path) # or use file
sftp_obj2 = sftp.open(path) # or use open
except:
print "Error! File not found!"
Upvotes: 3